skip to Main Content

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


  1. You could use Object.values for both cases (object and array):

    function sum(...args){
      if (args.length === 1 && args[0] && typeof args[0] === 'object') {
        args = Object.values(args[0]);
      }
      return args.reduce((a,b) => a + b);
    }
    
    console.log(sum([5,4,3,2,1]));
    console.log(sum(5,4,3,2,1));
    console.log(sum({a:5,b:4,c:3,d:2,e:1}));
    Login or Signup to reply.
  2. 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
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search