Skip to content

Instantly share code, notes, and snippets.

@conundrumer
Created January 7, 2018 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save conundrumer/8907ece56c19332be64fc77d6720714a to your computer and use it in GitHub Desktop.
Save conundrumer/8907ece56c19332be64fc77d6720714a to your computer and use it in GitHub Desktop.
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