Glenn
Glenn

Reputation: 5081

How to call different functions using an argument?

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!

Upvotes: 1

Views: 52

Answers (2)

Ionică Bizău
Ionică Bizău

Reputation: 113465

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)

Upvotes: 3

Akhilesh
Akhilesh

Reputation: 968

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');

Upvotes: 0

Related Questions