Created
June 29, 2019 05:41
-
-
Save stefanfrede/d29d42c42d7a464cf683c8204d65af1a to your computer and use it in GitHub Desktop.
A alternate approach to write a switch statement that supports composability and reusability.
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
// Example returns for illustration only. | |
const cases = { | |
alpha() { | |
return [ "Alpha", arguments.length ]; | |
}, | |
beta() { | |
return [ "Beta", arguments.length ]; | |
}, | |
_default() { | |
return [ "Default", arguments.length ]; | |
} | |
}; | |
const delegator = (key, ...args) => { | |
const delegate = cases.hasOwnProperty(key) | |
? cases[key] // Derive the method to delegate operation to | |
: cases._default; // Assign the default case handler | |
// The scope arg could be set to something specific, | |
// in this case, null will suffice | |
return delegate.apply(null, args); | |
}; | |
// Put the API to work: | |
delegator( "alpha", 1, 2, 3, 4, 5 ); | |
//=> [ "Alpha", 5 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment