-
-
Save A1rPun/f5b382812d583be9f97fba323c4193f1 to your computer and use it in GitHub Desktop.
JavaScript function pattern matching inspired by F#'s & renanpvaz gist
This file contains 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
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