Skip to content

Instantly share code, notes, and snippets.

@netpoetica
Last active January 13, 2018 08:26
Show Gist options
  • Save netpoetica/f92b839e0d7abc2ecf5e to your computer and use it in GitHub Desktop.
Save netpoetica/f92b839e0d7abc2ecf5e to your computer and use it in GitHub Desktop.
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
Copy link
Author

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