I have a data, I need to call one of three methods, how to achieve more elegant?

Viewed 33

The scene is like the following code, but the reality does not feel very good.

//example
const data = [];
const index = 0;

if (index === 0) {
  A(data);
} else if (index === 1) {
  B(data);
} else if (index === 2) {
  C(data);
}

1 Answers

First: You could declare an object that has all of your functions

let functions = {
   0: function(data) { A(data) },
   1: function(data) { B(data) },
   2: function(data) { C(data) }
}

And then you can use it like this:

functions[index](data);

I'm not saying it's better than what you have currently but its different. Maybe it helps you.

Related