Sorry if this has been asked before, but I couldn't find the words to search that would give me the answer I'm looking for.
I'm writing a script that contains a helper function, which, in turn, can call one of several functions which all take the same parameters. In this helper function, I end up having strings of this:
if funcName="func1":
func1(p1, p2, p3)
elif funcName="func2":
func2(p1, p2, p3)
elif funcName="func3":
func3(p1, p2, p3)
...
I know that I could use another helper function that would also take the funcName string and distribute it to the appropriate function, but is there a better way to do it? What my brain wants to do is this:
funcName(p1, p2, p3)
That way I could call an arbitrary function name if I want to. Is something like that possible?
Yes, you can, by using a dict mapping names to functions:
funcs = dict(
func1=func1,
func2=func2,
func3=func3
)
funcs[funcName](p1, p2, p3)
If you put the functions inside an object like so:
var funcs =
{
f1: function() {},
f2: function() {},
f3: function() {}
}
You can do funcs['f1']() for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With