Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum of arguments

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading