Arrow Function of JavaScript question - Multiple Arrow Function nesting

Viewed 131
3 Answers

Let's try and break it down.

(sum => el => sum += el) , is equivalent to:

const mySumFunction = (sum) => {

   const addToSum = (el) => { 
      sum += el;
      return sum;
   }

   return addToSum;
}

This is a function that takes in a parameter - a starting sum. The sum parameter is also local variable within the function's scope.

When you call mySumFunction, it returns another function that adds to the local scoped variable sum and returns the total sum so far.

In effect, it creates a "function with memory" that returns the sum of everything that has been passed into it so far.

You can test this out as follows:

cumilativeSum = mySumFunction(0)
console.log(v(1)) // returns 1
console.log(v(1)) // returns 2
console.log(v(4)) // returns 6

Now let's look at the code as a whole.

let runningSum = nums => nums.map((sum => el => sum += el)(0));

The entire snippet passed into the map function: (sum => el => sum += el)(0) creates a "sum function with memory" that starts at 0, as we figured out above.

We're passing each of the numbers in an array to it and creating an array with the cumulative sum.

Original function

let runningSum = nums => nums.map((sum => el => sum += el)(0));

(sum => el => sum += el) is

function f1(sum) {
  return function f2(el) {
    return sum += el;
  }
}

(or in arrow format as shown by @Alterlife)

The original function then transforms into

let runningSum = nums => nums.map(f1(0));

then nums.map(f1(0));

becomes

const result = [];
const f2 = f1(0);

for(let i = 0; i < nums.length; ++i) {
  const num = nums[i];
  result.push(f2(num));
}

So all together, the original function transforms into

const nums = [1,2,3,4];
function f1(sum) {
  return function f2(el) {
    return sum += el;
  }
}
const result = [];
const f2 = f1(0);

for(let i = 0; i < nums.length; ++i) {
  const num = nums[i];
  result.push(f2(num));
}
console.log(result);

Let's take (sum => el => sum += el)(0) this self invocation arrow function for 1st iteration of map. Up on execution it return another arrow function el => sum += el. The value of sum is 0 which is passed as argument. Now keep come to our map 1st iteration

let runningSum = nums => nums.map(el => sum = 0 + el);

It returns 1. So, for the 2nd iteration, the value of the sum is 1 and el is 2. so it returns 3, then 6 and then 10.

let runningSum = (nums) =>
  nums.map(
   (function (sum) {
         return (el) => (sum += el);
   })(0)
  );
console.log(runningSum([1, 2, 3, 4]));
Related