Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacement for switch statements?

Tags:

javascript

Any way to replace this switch statement for object?

 Object.keys(data).forEach(key => {
    switch (true) {
        case key === '1':
            Store.get1();
            return;
        case key === '2':
            get2();
            return;
        case key === '4':
            get4(4);
            return;
        case key === '5':
            get5({value1 = 5.value1, value2 = 5.value2});
            return;
        default:
            break;
    }
  })

to replace it with something like this:

       Object.keys(data).forEach(key => {
          const keyMap = {
        1: Store.get1(),
        2: get2(),
        3: get3(),
        4: get4(),
        5: get5({value1 = 5.value1, value2 = 5.value2}),
        };
        return keyMap[key];

but this way every function in keyMap just gets triggered every time.

  1. i need get2() without store, because its just a function in the upper scope.
  2. imagine 5 as an object 5: { value1: something, value2: something}
like image 500
dobbey Avatar asked Jan 26 '23 15:01

dobbey


1 Answers

Syntax errors in the original aside, just have the functions in the lookup table, then call them:

const keyMap = {
  1: Store.get1,
  2: get2,
  3: get3,
  4: get4,
  5: get5,
};

Object.keys(data).forEach(key => {
  return keyMap[key]();
});
like image 122
AKX Avatar answered Jan 30 '23 12:01

AKX