Skip to content

Instantly share code, notes, and snippets.

@nickjacob
Created November 6, 2012 07:50
Show Gist options
  • Save nickjacob/4023298 to your computer and use it in GitHub Desktop.
Save nickjacob/4023298 to your computer and use it in GitHub Desktop.
Javascript is the perfect language for dispatch tables
/* Why would you ever need a switch statement in javascript? */
var switchy = {
1: function(x){ return x*x; },
pizza: function(x){ return x*x*X }
};
var bar = switchy[foo](10);
// what if you could extend it with regex?
function switchy(cases){
this.cases = cases;
return function(match){
if(match instanceof Regexp){
for(var i in cases){ if(match.test(cases[i])){ return cases[i]; } };
} else {
return cases[match];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment