Last Updated: February 25, 2016
·
503
· thegleep

Faster than a switch statement

Instead of this:

switch(x) {
  case "First":
    dosomething();
    break;
  case "first":
    dontdosomething();
    break;

  case default:
    dontdoanything();
    break;
}

try this:

var switchAlternative = {
  First: dosomething,
  first: dontdosomething,
  Switch: function(opt) {
    var func = switchAlternative[opt];
    if (typeof(func) == "undefined") {
      return dontdoanything();
    }
    else {
      return func[opt]();
    }
  }
}