Skip to content

Instantly share code, notes, and snippets.

@dwickstrom
Last active January 1, 2018 12:24
Show Gist options
  • Save dwickstrom/3f2e630e29b07d7f342c0ff420ce341c to your computer and use it in GitHub Desktop.
Save dwickstrom/3f2e630e29b07d7f342c0ff420ce341c to your computer and use it in GitHub Desktop.
JS pattern matching
// fooIsBar :: Int -> String
const fooIsBar = x =>
x == 1 ? 'one'
: x == 2 ? 'two'
: x == 3 ? 'three'
: x == 4 ? 'four'
: /* or */ 'too much'
// sign :: Int -> Int
const sign = x =>
x > 0 ? 1
: x === 0 ? 0
: x < 0 ? -1
: /* else */ throw new TypeError('Not an integer')
// take :: Int -> [a] -> [a]
const take = n => xs =>
xs.length === 0 ? []
: n === 0 ? []
: /* otherwise */ [head (xs), ...take (n-1)
(tail(xs))]
// factorial :: Int -> Int
const factorial = n =>
n === undefined ? 0
: n === 0 ? 1
: /* otherwise */ n * factorial (n -1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment