Created
January 7, 2018 17:21
-
-
Save conundrumer/8907ece56c19332be64fc77d6720714a 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