Skip to content

Instantly share code, notes, and snippets.

@oslego
Created January 20, 2016 15:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oslego/bdfdf7e4497d78edcac3 to your computer and use it in GitHub Desktop.
Save oslego/bdfdf7e4497d78edcac3 to your computer and use it in GitHub Desktop.
Alternative JS solution to `switch` statement or suite of `if` statements.
/*
Alternative solution to switch statement or a suite of if statements
using an object literal in JS to store cases.
if (type == "save") { }
if (type == "delete") { }
*/
function operation(type, opts) {
var handler = {
"save" : function(opts) { console.log("save") },
"delete": function(opts) { console.log("delete") }
}[type]
handler ? handler.call(this, opts) : console.error('Unkown type: ' + type);
}
operation('save', {})
operation('delete', {})
operation('fake', {})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment