Using reduce to realize function chain call in es6

Today, I checked and learned some of the application scenarios of reduce api on the Internet, and also followed the implementation of the code in the Google console. I read an article
requirements: add () (1: add () (2) (3 br 4) (7page8pint 9) () final output / / 34
this function is implemented with reduce! Has anyone given an elegant code

Apr.09,2021

this site has a similar answer to


you didn't say the specific rules, according to your example, the parameters for the first call and the last call are empty, so:

function add(){
  let arr = [];
  return function fn(){
    if(arguments.length>0){
      arr.push(...arguments)
      return fn;
    }
    return arr.reduce((sum,v)=>sum+v);
  }
}

console.log(add()(1,2)(3,4)(7,8,9)())//34

const add = function() {
  let v = 0, 
    f = function(){
    v = [].reduce.call(arguments, (a, b) => a + b, v);
    return arguments.length ? f : v;
  };
  return f
};
console.log(add()(1, 2)(3, 4)(7, 8, 9)())
Menu