Created
January 21, 2022 02:48
-
-
Save suissa/554c57c37717c80583f3a5bdf5834582 to your computer and use it in GitHub Desktop.
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
function trampoline(f) { | |
return function trampolined(...args) { | |
let result = f.bind(null, ...args); | |
while (typeof result === 'function') result = result(); | |
return result; | |
}; | |
} | |
function _factorial(n) { | |
if (n <= 1) return 1; | |
return n * _factorial(n - 1); | |
} | |
const factorial = trampoline(function _factorial(n, acc = 1) { | |
if (n <= 1) return acc; | |
return () => _factorial(n - 1, n * acc); | |
}); | |
console.log(factorial(6)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment