0

I am looking at this exercise:

1. es6-sum-numbers

You need to define a function which will add numbers and return the sum.
Use rest operator feature of ES6+ to accept numbers from the user and calculate its sum.

Example:

sum(1) // 1
sum(1,2) // 3
sum(1,2,4) // 7
sum(1,2,3,4,5,6,7) // 28

The template code to work from is given as follows:

const sum = () => {

}
module.exports = {sum}

What is the correct way to solve this exercise, I'm new to es6 and I can't understand?

trincot
  • 317,000
  • 35
  • 244
  • 286

1 Answers1

0

The "rest operator" that the challenge speaks of is a misnomer. This is not an operator. It is a specific syntax that can be used when declaring a function parameter list. Mozilla Contributors have an article on this syntax, called rest parameter syntax:

The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.

The article continues with an example, that is exactly the function you are asked to provide (how lucky can you be, huh?):

function sum(...theArgs) {
  let total = 0;
  for (const arg of theArgs) {
    total += arg;
  }
  return total;
}

console.log(sum(1, 2, 3));
// expected output: 6

console.log(sum(1, 2, 3, 4));
// expected output: 10

The above function definition can replace the placeholder (but don't touch the module.exports line). Or with arrow syntax (as used in the template):

const sum = (...theArgs) => {
  let total = 0;
  for (const arg of theArgs) {
    total += arg;
  }
  return total;
};

module.exports = {sum};

The template code you got to start with also promotes a bad habit: to drop the ; statement separators and count on the automatic semicolon insertion algorithm. Don't go with that. Type the semicolons.

trincot
  • 317,000
  • 35
  • 244
  • 286