Skip to content

Instantly share code, notes, and snippets.

@A1rPun
Forked from renanpvaz/f.js
Last active April 15, 2019 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save A1rPun/f5b382812d583be9f97fba323c4193f1 to your computer and use it in GitHub Desktop.
Save A1rPun/f5b382812d583be9f97fba323c4193f1 to your computer and use it in GitHub Desktop.
JavaScript function pattern matching inspired by F#'s & renanpvaz gist
fun = (variations, matchIndex = 0) => (...appliedArgs) => (variations[appliedArgs[matchIndex]] || variations._)(...appliedArgs)
luck = fun({
7: () => "LUCKY NUMBER SEVEN",
_: () => "Sorry, you're out of luck, pal!",
})
luck(7)
// "LUCKY NUMBER SEVEN"
luck(1)
// "Sorry, you\'re out of luck, pal!"
// if the function is recursive:
fib = fun({
0: () => 0,
1: () => 1,
_: n => fib(n - 1) + fib(n - 2),
})
fib(0)
// 0
fib(1)
// 1
fib(7)
// 13
fibonacciTail = n => fibonacciIter(n, 0, 1)
fibonacciIter = fun({
0: (_n, prevFib) => prevFib,
_: (n, prevFib, fib) => fibonacciIter(n - 1, fib, prevFib + fib),
})
fibonacciTail(0)
// 0
fibonacciTail(1)
// 1
fibonacciTail(78)
// 8944394323791464
factorial = fun({
0: () => 1,
_: n => n * factorial(n - 1),
})
factorial(6)
// 720
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment