Skip to content

Instantly share code, notes, and snippets.

Created October 29, 2012 18:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/3975291 to your computer and use it in GitHub Desktop.
Save anonymous/3975291 to your computer and use it in GitHub Desktop.
An evaluating switch in JavaScript
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]
);
@DBJDBJ
Copy link

DBJDBJ commented Nov 6, 2014

This also will work:

   console.log( 
                  swtch(2, ["A","B","C"] )
   );   

No need to stop at objects :) This is not a switch logic though, this is just a lookup.
dbj.cond https://www.npmjs.org/package/dbj.cond leads to simpler syntax and provides comparison logic, just like switch() does:

             dbj.cond( ["A","B","C"] , "C", "C is found in input!", "C is not found");
             //=> return "C is found in input!"

Voila :)

@anthonybrown
Copy link

DBJDBJ thanks for the link to the dbj package

@kobenauf
Copy link

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