Skip to content

Instantly share code, notes, and snippets.

@scriptype
Last active June 20, 2018 23:18
Show Gist options
  • Save scriptype/866e058012915a08ba3598d555e85e6d to your computer and use it in GitHub Desktop.
Save scriptype/866e058012915a08ba3598d555e85e6d to your computer and use it in GitHub Desktop.
take(): Switch-case as an expression
/*
* It takes an expression and a handler object
* that consists of potential actual values of
* the given expression.
*
* The function calls either the
* matching method or the default defined in
* handler object (if defined).
*/
function take(expression, handler) {
return handler[expression]
? handler[expression]()
: handler.default
? handler.default()
: undefined
}
/* EXAMPLE USE */
// Some hardcoded value.
var foo = 'foo'
// A variable whose value is assigned randomly.
var bar = Math.random() >= .66
? ' bar'
: Math.random() >= .5
? ' baz'
: ''
// In effect, computedValue will be random.
var computedValue = foo + bar
/*
* Take computedValue as an expression and
* assign a value to lorem depending on the
* computedValue.
* Pretty much the same logic that goes into
* a switch-case statement.
*/
var lorem = take(computedValue, {
foo: () =>
'it is foo',
['foo bar']: () =>
'it is foo bar',
default: () =>
'none'
})
console.log('lorem:', lorem)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment