Last active
March 1, 2018 17:30
-
-
Save abrahamjuliot/a02b4454837f75e6652a90354817580f to your computer and use it in GitHub Desktop.
Functional Switch in Javascript
This file contains hidden or 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
const callIfFunction = x => x instanceof Function ? x() : x | |
const choose = switchFn => // cache cases | |
caseVal => callIfFunction(switchFn(caseVal)[caseVal] || switchFn().default) // get case | |
const agree = (x, ...list) => // agree on a fall through set | |
list.find(val => x === val) || list[0] | |
// make as many of these as needed | |
const colors = choice => ({ | |
['sky']: 'blue', | |
[agree(choice, | |
'flower', | |
'lipstick', | |
'purse')]: 'purple', | |
[(() => 'skittles')()]: () => 'rainbow', | |
default: 'white' | |
}) | |
// cache colors | |
const color = choose(colors) | |
// get color later | |
color('skittles') // => 'rainbow' | |
color('lipstick') // => 'purple' | |
color() // => 'white' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment