Skip to content

Instantly share code, notes, and snippets.

@abrahamjuliot
Last active March 1, 2018 17:30
Show Gist options
  • Save abrahamjuliot/a02b4454837f75e6652a90354817580f to your computer and use it in GitHub Desktop.
Save abrahamjuliot/a02b4454837f75e6652a90354817580f to your computer and use it in GitHub Desktop.
Functional Switch in Javascript
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