* fix: remove example code from challenge seed * fix: remove declaration from solution * fix: added sum variable back in * fix: reverted description back to original version * fix: added examples to description section * fix: added complete sentence Co-Authored-By: Oliver Eyton-Williams <ojeytonwilliams@gmail.com> * fix: corrected typo Co-Authored-By: Manish Giri <manish.giri.me@gmail.com> * fix: reverted to original desc with formatted code * fix: removed unnecessary code example from description section Co-Authored-By: Oliver Eyton-Williams <ojeytonwilliams@gmail.com> * fix: failiing test on iterate through array with for loop * fix: changed to Only change this line Co-Authored-By: Manish Giri <manish.giri.me@gmail.com> Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com> Co-authored-by: Manish Giri <manish.giri.me@gmail.com> Co-authored-by: moT01 <tmondloch01@gmail.com>
2.1 KiB
2.1 KiB
id, title, challengeType, forumTopicId
id | title | challengeType | forumTopicId |
---|---|---|---|
587d7b88367417b2b2512b47 | Use the Rest Parameter with Function Parameters | 1 | 301221 |
Description
function howMany(...args) {
return "You have passed " + args.length + " arguments.";
}
console.log(howMany(0, 1, 2)); // You have passed 3 arguments.
console.log(howMany("string", null, [1, 2, 3], { })); // You have passed 4 arguments.
The rest parameter eliminates the need to check the args
array and allows us to apply map()
, filter()
and reduce()
on the parameters array.
Instructions
sum
using the rest parameter in such a way that the function sum
is able to take any number of arguments and return their sum.
Tests
tests:
- text: The result of <code>sum(0,1,2)</code> should be 3
testString: assert(sum(0,1,2) === 3);
- text: The result of <code>sum(1,2,3,4)</code> should be 10
testString: assert(sum(1,2,3,4) === 10);
- text: The result of <code>sum(5)</code> should be 5
testString: assert(sum(5) === 5);
- text: The result of <code>sum()</code> should be 0
testString: assert(sum() === 0);
- text: The <code>sum</code> function should use the <code>...</code> rest parameter on the <code>args</code> parameter.
testString: assert(code.replace(/\s/g,'').match(/sum=\(\.\.\.args\)=>/));
Challenge Seed
const sum = (x, y, z) => {
const args = [x, y, z];
return args.reduce((a, b) => a + b, 0);
}
Solution
const sum = (...args) => {
return args.reduce((a, b) => a + b, 0);
}