javascriptdecoratorrest-parameters

unpacking rest (...theArgs) parameter before passing it to the function


I am trying to call a function required number of times. To solve this, I am creating a function that takes rest parameters and iterating through the first argument. I am unable to unpack the rest arguments and pass it to the function. Is there a way that I could unpack and pass it to the function as parameters. Below is my working code. Is there a better way to make it work?

function hello(name) {
  console.log("Hello "+ name);
}

function greet(name,time_of) {
  console.log("Good " + time_of +" " +name);
}

function foo(times,x, ...args) {
    for(i=0;i<times;i++) {
    x(arguments)
    //x(args); //works good for hello() but not for greet(). Doesn't pass them to second argument
    x(args[0],args[1]); //This works but not scalable 
    //args.map((element) => x(element)); 

  }
}

foo(2,hello,"Myname");
foo(3,greet,"Myname","Afternoon");

Solution

  • Just spread the args out again:

    function hello(name) {
      console.log("Hello " + name);
    }
    
    function greet(name, time_of) {
      console.log("Good " + time_of + " " + name);
    }
    
    function foo(times, x, ...args) {
      for (i = 0; i < times; i++) {
        x(...args)
      }
    }
    
    foo(2, hello, "Myname");
    foo(3, greet, "Myname", "Afternoon");