I am facing a challenge with a collection of arbitrary functions and a method that takes a function name along with an object or array of parameters to call the respective function. The issue arises from the varying number of inputs in these functions, some of which have optional fields with default values. I am struggling to find a universal approach to match the parameters with the function inputs.
One workaround for handling array arguments is to directly invoke the function using the ...
operator: func(...args)
. However, this solution falls short when it comes to dealing with objects. Is there a way to align object values with function inputs based on their keys?
To illustrate the scenario further, consider the following abstract example:
const funcs = {
func1: (arg1, arg2, arg3 = 'something') => .....does something
func2: () => ....does something
func3: (anotherArg1) => ...does something
}
function callFunction(method: string, args: unknown[]| object) {
if (Array.isArray(args)) {
return funcs[method](...args)
}
else (if args instanceof Object) {
//... Here I need to parse the args and call the function in "funcs" object.
}
}