Created
October 29, 2012 18:02
-
-
Save anonymous/3975291 to your computer and use it in GitHub Desktop.
An evaluating switch in JavaScript
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
function swtch(value, cases) { | |
return cases[value]; | |
} | |
var foo = 3; | |
console.log( | |
swtch(foo, { | |
1: "one", | |
2: "two", | |
3: "three", | |
4: "four", | |
5: "five" | |
}) | |
); | |
// or, as this is minimal syntactic sugar... the more obfuscated version with one less function call: | |
console.log( | |
{ | |
1: "one", | |
2: "two", | |
3: "three", | |
4: "four", | |
5: "five" | |
}[foo] | |
); |
While this is clever and fun, it's not obvious and not as maintainable. Unless there is a big benefit, less readable code should be avoided.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
DBJDBJ thanks for the link to the
dbj
package