I am practicing using ...rest
operator to pass arguments to functions. I have run into an issue that I’m unable to resolve for when passing an object to the function.
Here is the function:
function sum(...args){
if (args.length === 1 && Array.isArray(args[0])) {
args = args[0];
}
return args.reduce((a,b) => a + b);
}
console.log(sum([5,4,3,2,1])); // Returns 15
console.log(sum(5,4,3,2,1)); // Returns 15
console.log(sum({a:5,b:4,c:3,d:2,e:1})); // Returns {a:5,b:4,c:3,d:2,e:1}
I’m stuck at how to test for and handle the last use case.
2
Answers
You could use
Object.values
for both cases (object and array):Convert your object to an array with
Object.values
, passing an object instead of an array is an overkill:Also you could possibly improve your function with
Array::flat()
.That way it will behave the same as
Array::concat()
. I like that.I wouldn’t convert an object to an array automatically inside
sum
but if you need: