Although you can do that, I strongly recommend you don't. It requires using new Function or eval, which is normally worth avoiding as it fires up a JavaScript parser (and in the wrong hands, exposes a vulnerability by offering arbitrary code execution). I'd just export a version that accepts a single array parameter rather than discrete parameters. People can easily call it with discrete arguments: myFunc([firstValue, secondValue, thirdValue]).
But if the text in the array comes from a safe source, you can do it with new Function.
In ES2015+:
function realMyFunc(options) {
// ...`options` is an array of the parameters
};
export const myFunc = new Function(...theArray, "return realMyFunc([" + theArray.join(", ") + "]);");
Example:
const theArray = ["option1", "option2", "option3"];
function realMyFunc(options) {
console.log(options);
};
const myFunc = new Function(...theArray, "return realMyFunc([" + theArray.join(", ") + "]);");
console.log("myFunc:", myFunc);
myFunc("a", "b", "c");
.as-console-wrapper {
max-height: 100% !important;
}
Or in ES5:
var theArray = ["option1", "option2", "option3"];
function realMyFunc(options) {
console.log(options);
};
var myFunc = new Function("return function(" + theArray.join(", ") + ") { return realMyFunc([" + theArray.join(", ") + "]); }")(); // Note the added () at the end
console.log("myFunc:", myFunc);
myFunc("a", "b", "c");
.as-console-wrapper {
max-height: 100% !important;
}
Again, though, I'd just export a version that accepts a single array parameter rather than dynamically generating a version that accepts discrete parameters.
Spread Syntax?Function.prototype.apply?