Home > Software engineering >  Sum of arguments
Sum of arguments

Time:11-24

I need help, friends!

We need to implement the sum function, which takes an unlimited number of numbers as arguments and returns their sum.

A function call without arguments should return 0. If the argument is not a number and cannot be cast to such, you should ignore it. If it can be reduced to a number, then bring it and add it, like an ordinary number.

Usage example:

console.log(
    sum(1, 2, 3, 4, 5, 6),
); // 21
console.log(
    sum(-10, 15, 100),
); // 105
console.log(
    sum(),
); // 0
console.log(
    sum(1, 'fqwfqwf', {}, [], 3, 4, 2, true, false),
); // 11. true = 1

My try:

const sum = (...arr) => {
    return arr.reduce((a, i) => {
      if (isNaN(i)) return Number(i)
      return a    Number(i)
    }, 0)    
};

I cannot ignore the values ​​of those data types that cannot be converted to a number and convert the values ​​to a number, if possible.

I would be very grateful if you help

CodePudding user response:

You can try enforcing type-coercion (convert array's item to number). If JS successfully coerces, then add it, else, fallback to 0 :

You can also make it one-liner as:

const sum = (...arr) => arr.reduce((a, i) => a   ( i || 0), 0);

const sum = (...arr) => {
  return arr.reduce((a, i) => {
    return a   ( i || 0);
  }, 0);
};

console.log(sum(1, 2, 3, 4, 5, 6)); // 21
console.log(sum(-10, 15, 100)); // 105
console.log(sum()); // 0
console.log(sum(1, "fqwfqwf", {}, [], 3, 4, 2, true, false)); // 11. true = 1
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can do as:

const sum = (...arr) => arr.filter(Number).reduce((a, c) => a   c, 0);

console.log(sum(1, 2, 3, 4, 5, 6)); // 21
console.log(sum(-10, 15, 100)); // 105
console.log(sum()); // 0
console.log(sum(1, "fqwfqwf", {}, [], 3, 4, 2, true, false)); // 11. true = 1
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related