Skip to content

Instantly share code, notes, and snippets.

@stefanfrede
Created June 29, 2019 05:41
Show Gist options
  • Save stefanfrede/d29d42c42d7a464cf683c8204d65af1a to your computer and use it in GitHub Desktop.
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.
// 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