Last active
January 13, 2018 08:26
-
-
Save netpoetica/f92b839e0d7abc2ecf5e to your computer and use it in GitHub Desktop.
Use functions + dictionary instead of Switch/Case (illustrative purposes)
This file contains hidden or 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
// Setup | |
function onGet(){ /* .. */ } | |
function onDelete(){ /* .. */ } | |
function onPost(){ /* .. */ } | |
var onPut = onPost; // Sharing functionality. | |
// Bad | |
function processRequest(method){ | |
var requestMethod = method.toLowerCase(); | |
switch(requestMethod){ | |
case "get": | |
onGet(); | |
break; | |
case "delete": | |
onDelete(); | |
break; | |
// Can be dangerous, also not good for readability | |
case "post": | |
case "put": | |
onPost(); | |
break; | |
} | |
} | |
// Good | |
// Extra Setup | |
var methodHandlers = { | |
"get": onGet, | |
"delete": onDelete, | |
"post": onPost, | |
"put": onPut | |
}; | |
function processRequest(method){ | |
var requestMethod = method.toLowerCase(); | |
// Get reference to the method so we don't do a lookup twice | |
var handler = methodHandlers[requestMethod]; | |
// If we have a handle, run it. | |
if(typeof handler === 'function') handler(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Doesn't perform as well, by just a bit, but is much more JavaScripty: http://jsperf.com/case-against-switch-case