Skip to content

Instantly share code, notes, and snippets.

@kwijibo
Last active October 6, 2016 11:08
Show Gist options
  • Save kwijibo/e0d5cbd51c8cb0ff48fbde40f6f535ac to your computer and use it in GitHub Desktop.
Save kwijibo/e0d5cbd51c8cb0ff48fbde40f6f535ac to your computer and use it in GitHub Desktop.
JS pattern matching
const Pattern = testers => transformers => val => {
const match = Object.keys(testers).find(k => testers[k](val))
return transformers[match](val)
}
const Num = Pattern({
Odd: n => n % 2,
Even: n => !(n % 2)
})
const numberToString = Num({
Odd: x => '+',
Even: x => '-'
})
;[4,8,15,16,23,42].map(numberToString).join('') //=> "--+-+-"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment