Skip to content

Instantly share code, notes, and snippets.

@suissa
Created January 21, 2022 02:48
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 suissa/554c57c37717c80583f3a5bdf5834582 to your computer and use it in GitHub Desktop.
Save suissa/554c57c37717c80583f3a5bdf5834582 to your computer and use it in GitHub Desktop.
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