Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Use functions + dictionary instead of Switch/Case (illustrative purposes)
// 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();
}
@netpoetica

This comment has been minimized.

Copy link
Owner Author

commented Dec 24, 2014

Doesn't perform as well, by just a bit, but is much more JavaScripty: http://jsperf.com/case-against-switch-case

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.