Last active
November 19, 2015 02:44
-
-
Save kminardo/d036ad3e6e44d16ae3b7 to your computer and use it in GitHub Desktop.
Small snippet of useful code
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
var cases, delegator; | |
// Example returns for illustration only. | |
cases = { | |
alpha: function() { | |
// statements | |
// a return | |
return [ "Alpha", arguments.length ]; | |
}, | |
beta: function() { | |
// statements | |
// a return | |
return [ "Beta", arguments.length ]; | |
}, | |
_default: function() { | |
// statements | |
// a return | |
return [ "Default", arguments.length ]; | |
} | |
}; | |
delegator = function() { | |
var args, key, delegate; | |
// Transform arguments list into an array | |
args = [].slice.call( arguments ); | |
// shift the case key from the arguments | |
key = args.shift(); | |
// Assign the default case handler | |
delegate = cases._default; | |
// Derive the method to delegate operation to | |
if ( cases.hasOwnProperty( key ) ) { | |
delegate = cases[ key ]; | |
} | |
// The scope arg could be set to something specific, | |
// in this case, |null| will suffice | |
return delegate.apply( null, args ); | |
}; | |
// 7.A.1.3 | |
// Put the API in 7.A.1.2 to work: | |
delegator( "alpha", 1, 2, 3, 4, 5 ); | |
// [ "Alpha", 5 ] | |
// Of course, the `case` key argument could easily be based | |
// on some other arbitrary condition. | |
var caseKey, someUserInput; | |
// Possibly some kind of form input? | |
someUserInput = 9; | |
if ( someUserInput > 10 ) { | |
caseKey = "alpha"; | |
} else { | |
caseKey = "beta"; | |
} | |
// or... | |
caseKey = someUserInput > 10 ? "alpha" : "beta"; | |
// And then... | |
delegator( caseKey, someUserInput ); | |
// [ "Beta", 1 ] | |
// And of course... | |
delegator(); | |
// [ "Default", 0 ] | |
From https://github.com/rwaldron/idiomatic.js/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment