简体   繁体   中英

Javascript function that takes any number of inputs and called multiple times and gives the result

I wrote this function that solves the problem:

'use strict';

function myAdd(...args) {
  let sum = 0;
  const f = (...args2) => {
        for (const val of args2) sum += val;
        return f;
  }
  
  f.valueOf = () => sum;
  
  return f(...args);
}

let sumFour = myAdd(2)(2);
console.log(+sumFour(2)); // expected 6
console.log(+sumFour(2)); //expected 6

However, the logs are:

console.log(+sumFour(2)); // outputs 6
console.log(+sumFour(2)); // outputs 8

I think I know the problem which is whenever the function sumFour is called sum is being modified and the next time is called it is not 4 anymore. How can I change this function to solve this bug?

You can call a function with dynamic number of arguments.

If you use ES5 operator

function add() {
    const args = Array.from(arguments);
    return args.reduce((acc, cur) => acc + cur);
}

//console.log(add(3, 4, 5, 6, 7, 8, 10, 40));   // 33

If you use ES6 spread operator

function sum(...args){
    return args.reduce((acc, cur) => acc + cur);
}

//console.log(sum(3, 4, 5, 6, 7, 8, 10, 40));    // 33

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM