Created
January 20, 2016 15:30
-
-
Save oslego/bdfdf7e4497d78edcac3 to your computer and use it in GitHub Desktop.
Alternative JS solution to `switch` statement or suite of `if` statements.
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
/* | |
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