2

I was wondering how to run one method for all args passed to function and return them

Here’s an example what i want to achieve:

const getAllData = (args) =>{
    args.map((arg)=> useDispatch(arg))
}
return args

and call it in another file for example

const [var1,var2,var3] = getAllData()

or

const allVars = getAllData([var1,var2,var3])
Olian04
  • 6,480
  • 2
  • 27
  • 54
  • 1
    `getAllData = (...args) => args.map((arg)=> useDispatch(arg))` however, I'm not sure why that's any better than just doing `[var1, var2, var3].map((arg)=> useDispatch(arg)` without making a separate function. – VLAZ Jun 23 '21 at 16:37

3 Answers3

5

What you have written is pretty close-- just use the rest params syntax to access the args as an array. Below is a processAll version of this that can accept a processing function and any number of variables to process, and will return them. See it in action by running the snippet.

const one = 1;
const two = 2;
const three = 3;

function processAll(processor, ...args) {
  const processedArgs = args.map((arg) => processor(arg));
  return processedArgs;
}

function multiplyByTwo(input) {
  return input * 2;
}

const [pTwo, pFour, pSix] = processAll(multiplyByTwo, one, two, three);

console.log(pTwo, pFour, pSix);
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
  • "*just use the spread operator two spread out the args.*" what you have is [rest parameters syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters) it's not spreading. – VLAZ Jun 23 '21 at 16:39
  • @VLAZ - good catch, thanks; updated now. – Alexander Nied Jun 23 '21 at 16:41
2

In es6 you can use rest parameter for that!

// Example ----
function add(...nums) {
  // Here nums will be an array
  const sum = nums.reduce((a, c) => a + c);
  console.log(sum);
}

add(1,2,3);
h-sifat
  • 1,455
  • 3
  • 19
1

I think you're looking for the arguments object. You can pass as many variables as you want to the function, and then just loop over arguments to get each of them.

function getAllData() {
    return Array.from(arguments).map(arg => useDispatch(arg))
}
const allVars = getAllData(var1, var2, var3);

You can also use "rest parameters" to get the arguments as an array.

const getAllData = (...args) =>  Array.from(args).map(arg => useDispatch(arg));
const allVars = getAllData(var1, var2, var3);
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • 2
    Arrow functions do not get their own `arguments` the same way they don't get their own `this` - they inherit `arguments` (if any) from the enclosing context. – VLAZ Jun 23 '21 at 16:38
  • @VLAZ Yes, I just realized that when I was testing the code. Thanks for pointing it out. Fixed :-) – gen_Eric Jun 23 '21 at 16:39