Infinite Currying Function

We use a simplistic way to create an infinite currying function in JavaScript, with the help of Object.assign and valueOf.
Object.assign here will catch all the secondary object properties and set them into the first object. In this example, our primary object is our function. So the valueOf we have marked will return the total of all the prepared arguments provided when called.

function currySum (...args) {
  console.log(args);
  return Object.assign(
    // bind args to current function
    currySum.bind(null, ...args),
    { 
      // args -> [ 1, 2, 3, 1, 2, 3 ]
      // return a function as valueOf
      // sum all array data with reduce
      valueOf: () => args.reduce((a, c) => a + c, 0)
    }
  );
}

// Infinite Currying Sum Function
+currySum(1)(2)(3)(1, 2, 3); // 12
(Visited 20 times, 1 visits today)

Leave a comment

Your email address will not be published. Required fields are marked *