Search code examples
javascriptrest-parameters

How to test for object passed as ...rest argument to a function


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.


Solution

  • Convert your object to an array with Object.values, passing an object instead of an array is an overkill:

    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(Object.values({a:5,b:4,c:3,d:2,e:1}))) //

    Also you could possibly improve your function with Array::flat(). That way it will behave the same as Array::concat(). I like that.

    function sum(...args){
      return args.flat().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(Object.values({a:5,b:4,c:3,d:2,e:1}))) // Returns 15
    console.log(sum(
      [5,4,3,2,1],
      5,4,3,2,1,
      Object.values({a:5,b:4,c:3,d:2,e:1})
    )); // Returns 45

    I wouldn't convert an object to an array automatically inside sum but if you need:

    function sum(...args){
      return args
        .map(arg => typeof arg === 'object' && !Array.isArray(arg) ? Object.values(arg) : arg)
        .flat()
        .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 15
    console.log(sum(
      [5,4,3,2,1],
      5,4,3,2,1,
      {a:5,b:4,c:3,d:2,e:1}
    )); // Returns 45