Skip to content

Instantly share code, notes, and snippets.

@entrptaher
Forked from conundrumer/asyncRecursive.js
Created January 7, 2018 17:48
Show Gist options
  • Save entrptaher/d6f51da11e700d3f7608b66dded1d24b to your computer and use it in GitHub Desktop.
Save entrptaher/d6f51da11e700d3f7608b66dded1d24b 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