How to run one method for any amout of varibles

Viewed 48

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])
3 Answers

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);

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);

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);
Related