DEV Community

loading...

Discussion on: My functional approach to HackerRank's 'Mini-Max Sum' challenge

Collapse
vonheikemen profile image
Heiker

I see your single purpose reduce and raise you a reduce that does a bunch of stuff (just for fun).

const add = (a, b) => a + b;
const print = ([a, b]) => console.log(`${a} ${b}`);
const repeat = (num, item) => Array.from({ length: num }, () => item);

const three_ops = ([first, ...rest]) => rest.reduce(
  (state, value) => [
    state[0], 
    Math.max(state[0], value),
    Math.min(state[0], value),
    add(state[3], value)
  ],
  repeat(4, first)
);

function miniMaxSum(arr) {
  const [,max,min,sum] = three_ops(arr);

  return [
    sum - max,
    sum - min
  ];
}

print(miniMaxSum([1,3,5,7,9]));
Enter fullscreen mode Exit fullscreen mode

Kids, don't do this at home.