0

I am looking for the best method of calling functions with variable names that all follow a specific rule. I am trying to avoid using eval() since there are so many problems about it online.

I have a system setup where different groups have a function that can be called based on their name EG Test group would have a function imported in called getValue_Test(params) and this function can be called for any group name EG getValue_Test2(params) would work if the group name was test2.

I have these functions being imported into the react component and just want to know the best way to call them without making giant switch statement since there will be hundreds of these functions.

Any help would be appreciated :) Thanks

2
  • if you did getValue('test', params) and made the group a variable and not hardcoded, then you wouldn't have this xy problem Commented May 3, 2022 at 17:06
  • The problem is these functions are all different and have to be hardcoded so this would just push the problem down into whatever file has that function @LawrenceCherone Commented May 3, 2022 at 17:11

1 Answer 1

2

If you've got some functions defined like this:

function foo() {}

function bar() {}

function baz() {}

You could put them in an object (or map):

const funcs = { foo, bar, baz };

Then you will be able to use a string to access and eventually call the function:

funcs["foo"](); // called foo

const key = "bar";

funcs[key](); // called bar

funcs.baz(); // called baz

However this is usually not recommended. It looks like you might want to use an array instead? Your function names differ only by a number that appears to be incrementing.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry my example is somewhat bad the names vary by more than just a number, Ill give this object stuff a shot tho ty

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.