Check if there are two items in an array whose sum is equal to a given value with es6-arrow function syntax

Viewed 207

The following code detects if in a given array arr there are two items whose sum is equal to the value given in the variable sum. To address this problem the complementary values (sum-item) are stored into a Set.

Although I know the arrow functions and how functional some() function works, the syntax is obscure to me and I struggle to understand.

const arr = [3,6,7];
const sum = 9;

const findSum = (arr,sum) =>
  arr.some((set => n =>
    set.has(n) || !set.add(sum-n)) (new Set));

console.log(findSum(arr,sum));

I can't understand the (new Set) inside the some function (is a sort of IIFE? ) and how n is initialized to an item of arr, in my understanding the code set would initialized to an item of arr.

Someone can explain me how does it work?

2 Answers

You could change th formatting and have a look to the parts of the callback.

findSum = (arr, sum) => arr.some(
    (set => n => set.has(n) || !set.add(sum - n))
    (new Set)
);

You find two parts, one

    (set => n => set.has(n) || !set.add(sum - n))

is a function expresion which returns a function.

The other part is is an instance of Set

    (new Set)

which calls the function expression immediately (IIFE (immediately-invoked function expression)) and acts as closure over set.

    (set =>                                     )
    (new Set)

The final part which works as callback is

            n => set.has(n) || !set.add(sum - n)

which takes a single value from the array, checks if the value is in the set or adds the delta to the set. Adding to a Set returns the instance and is truthy. This is unwanted and negated to prevent an early exit of the iteration.

const
    arr = [3, 6, 7],
    sum = 9,
    findSum = (arr,sum) => arr.some(
        (set => n => set.has(n) || !set.add(sum - n))
        (new Set)
    );

console.log(findSum(arr, sum));

Well if we transform the arrow function into normal ones it will be easier to understand.

const arrx = [3, 6, 7];
const sum = 9;

 const findSum2 = function(arr, sum) { //  (arr, sum) =>
  let search = function(set) { // set =>
    return function(n) { // n =>
      const r =
        set.has(n) || !set.add(sum - n); // same 
      return r;
    }
  }
  let init = search(new Set); // (..)(new Set) part
  return arr.some(init);
}

console.log(findSum2(arrx, sum));

Related