Home > other >  How to dynamically create arguments as functions from an array
How to dynamically create arguments as functions from an array

Time:08-26

I have an array of objects(can be of any length):

[
    {
        "operator": "sortBy",
        "value": "price"
    },
    {
        "operator": "startAt",
        "value": "7"
    },
    ...

]

where operator is a name of a function that can be imported from the JS module:

{
  sortBy: f(),
  startAt: f(),
  ...
}

and value is any value with a type of string or number.

How can I create functions from this array and pass them as arguments to another function?

For example:

import * as Utils from "@externalPackage";

const filters = [
    {
        "operator": "sortBy",
        "value": "price"
    },
    {
        "operator": "startAt",
        "value": "7"
    }
]

const anotherFunction = (arg1, arg2, ...) => ...
//this function can have any number of arguments

const helperFunction = (arr)=>//What should I do here with filters array to get a list of callable arguments(=>Utils.sortBy("price"), Utils.startAt(7)) ?//

const result = anotherFunction(helperFunction(filters)) 
                               ^ ^ ^
                               | | |
//This should be transformed in anotherFunction(Utils.sortBy("price"), Utils.startAt(7))//


CodePudding user response:

You can use Array.map() to map the functions then you can spread it in arguments of another function. Then use the syntax as the one in the example to run the functions.

Utils['sortBy']('price')

const Utils = {
  sortBy: (a) => `sortBy ${a}`,
  startAt: (b) => `startAt ${b}`
}

const filters = [{
    "operator": "sortBy",
    "value": "price"
  },
  {
    "operator": "startAt",
    "value": "7"
  }
]

const anotherFunction = (arg1, arg2) => {
  console.log(arg1);
  console.log(arg2);
  
  return ':)';
}


const result = anotherFunction(...filters.map((f) => Utils[f.operator](f.value)))

CodePudding user response:

Assuming you want the Util functions to be called immediately (e.g. they generate something, and that will be passed to the other function), you can use Array.map to map the filters into the results of calling the specified Util functions:

const mapFilters = (filters) => {
  return filters.map(({ operator, value }) => Utils[operator](value));
};

And then call the other function, spreading the resulting array as the parameters:

const result = anotherFunction(...mapFilters(filters));
  • Related