Pages

[JS] Use object instead of swictch case

If you find yourself writing switch-case or long if-else clauses based on string comparision condition, consider switching it to use object instead. Object in Javascript can be dynamically updated which makes it very flexible. It works as a map so lookup is quick. For example, if you have some code like below.



function doSomething(message) {
  console.log(message);
}

function handleInput(input) {
  switch(input) {
    case VALUE1: 
      doSomething(MESSAGE1);
      break;
    case VALUE2:
      doSomething(MESSAGE2);
      break;
    default:
      throw new Error('not supportted input ' + input);
  }
}

You can always rewrite it as following.

 
function handleInput(input) {
  inputMessage = {
    VALUE1: MESSAGE1,
    VALUE2: MESSAGE2
  }
  if (!inputMessage[input]) {
    throw new Error('not supportted input ' + input);
  }
  doSomething(inputMessage[input]);
}

The code is now shorter but more readable and can be easily expanded in the future.

No comments:

Post a Comment