-
-
Save entrptaher/d6f51da11e700d3f7608b66dded1d24b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 sumNaive (n, acc = 0) { | |
if (n === 0) { | |
return acc | |
} | |
return sumNaive(n - 1, acc + n) | |
} | |
// console.log(sumNaive(1000)) | |
// console.log(sumNaive(100000)) | |
function trampoline (fn) { | |
return (...args) => { | |
let result = fn(...args) | |
while (result instanceof Function) { | |
result = result() | |
} | |
return result | |
} | |
} | |
function sum (n) { | |
let baseSum = trampoline(function recursiveSum (m, acc = 0) { | |
if (m === 0) { | |
return acc | |
} | |
return () => recursiveSum(m - 1, acc + m) | |
}) | |
return baseSum(n) | |
} | |
// console.log(sum(1000)) | |
// console.log(sum(100000)) | |
function asyncTrampoline (fn) { | |
return async (...args) => { | |
let result = fn(...args) | |
while (result instanceof Function) { | |
result = await result() | |
} | |
return result | |
} | |
} | |
function sumAsync (n) { | |
let baseSum = asyncTrampoline(function recursiveSum (m, acc = 0) { | |
if (m === 0) { | |
return acc | |
} | |
return () => Promise.resolve(recursiveSum(m - 1, acc + m)) | |
}) | |
return baseSum(n) | |
} | |
sumAsync(1000).then(x => console.log(x)) | |
sumAsync(100000).then(x => console.log(x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment