Skip to content

Instantly share code, notes, and snippets.

/swtch.js
Created Oct 29, 2012

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

commented Feb 23, 2015

DBJDBJ thanks for the link to the dbj package

@kobenauf

This comment has been minimized.

Copy link

commented Dec 23, 2015

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
You can’t perform that action at this time.