Created
November 6, 2012 07:50
-
-
Save nickjacob/4023298 to your computer and use it in GitHub Desktop.
Javascript is the perfect language for dispatch tables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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