0

In the code below, power isn't a pure function (uses two global variables), how can i convert it into a pure function with just one input array as parameter?

const multiplyByFour = function (array) {
  return array.map((item) => item * 4);
};

const sumElements = function (array) {
  return array.reduce((total, num) => {
    return total + num;
  });
};

function power(arr) {
  let lengthArray = arr.length;
  let value = sumElements(multiplyByFour(arr));
  return Math.pow(value, lengthArray);
}

console.log(power([3, 4, 2]));
daego
  • 177
  • 1
  • 1
  • 10
  • Move the functions inside the function? – Spectric Feb 15 '23 at 00:48
  • 6
    It is in fact a pure function. Using a relatively global function that is itself pure does not make a function impure. – Pointy Feb 15 '23 at 00:48
  • What about passing them in an "operations" array which you reduce into the final output? `power([3,4,2],[multiplyByFour,sumElements,Math.pow])` – evolutionxbox Feb 15 '23 at 00:51
  • 4
    A pure function must not use global *mutable* variables. It may however use global constants (and usually will). – Bergi Feb 15 '23 at 00:55

0 Answers0