Skip to content

Instantly share code, notes, and snippets.

@greyaperez
Created December 9, 2015 19:31
Show Gist options
  • Save greyaperez/485a0aafb2d054a7ee81 to your computer and use it in GitHub Desktop.
Save greyaperez/485a0aafb2d054a7ee81 to your computer and use it in GitHub Desktop.
Enhanced version of switch
var x = 'b';
var y = 'd';
var caseHandlers = {
'a': caseHandlerMethod1,
'b': caseHandlerMethod2,
'c': caseHandlerMethod3,
'default': defaultHandlerMethod
};
switch2(caseHandlers,x);
switch2(caseHandlers,y);
function switch2(caseHandlingMap, val) {
// Case Matched to Handler
if (typeof caseHandlingMap[val] !== 'undefined') {
return caseHandlingMap[val]();
}
// None Matched, but Default Handler Available
else if (typeof caseHandlingMap['default'] !== 'undefined') {
return caseHandlingMap['default']();
}
// None Matched, No Default Handler Available
else {
return -1;
}
}
function caseHandlerMethod1 (val) { console.log('Handler 1 Invoked on value:', val); }
function caseHandlerMethod2 (val) { console.log('Handler 2 Invoked on value:', val); }
function caseHandlerMethod3 (val) { console.log('Handler 3 Invoked on value:', val); }
function defaultHandlerMethod (val) { console.log('Default/Fallback Handler Invoked:', val); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment