Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.