1

I have come up with the following solution for calling different functions based on an argument value. Is there a better/simpler way?

function mainFunction(input, category) {
  categories = {
    'category1': () => { return { /* return stuff */ }}
    'category2': () => { return { /* return stuff */ }}
  }
  return categories[category].call();
}

Thank you!

2
  • Is there any reason that category1 and category2 are inside mainFunction, other than to call them based on those string values? Would it make sense in the context of your program if those functions were defined outside of mainFunction? Commented Jul 14, 2019 at 4:49
  • @PatrickRoberts it's in a module so the mainFunction gets exported. Also, just to avoid passing the input arg for each function individually. Commented Jul 14, 2019 at 4:52

2 Answers 2

3

You could do directly categories[category]().

However, here is how I would do it, to avoid defining the categories object every time you call this function:

const actions = {
  category1: (a, b, c) => { console.log(a, b, c) },
  category2: () => { return { /* return stuff */ }},
  call: (category, ...args) => {
    if (!actions[category]) {
      throw new Error("Invalid category.")
    }
    return actions[category](...args);
  }
}

actions.call("category1", 42, 7, 0)

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

2 Comments

I like it. The input arg could be handled like actions.call('category1', 'some input')
@Alan Exactly :-) If you want to use the spread operator, that will be even fancier. See the edit.
0

You can try something like this.

function mainFunction(input, category) {
  const categories = {
    'category1': () => {  
      console.log('cat 1'); 
     },
    'category2': () => { 
      console.log('cat 1'); 
     }
  };
  
  if (categories[category]) {
   return categories[category]();
  } else {
    // throw error here
  }
 
}

mainFunction('test', 'category2');

Comments

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.