Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Prone to bugs! This is for learning and demonstration purposes only
let prev = 0, curr = 1;
// the generator
function* fibGen(n) {
const pos = 1;
for(let i=pos; i < n; ++i) {
[prev, curr] = yield asyncFetchPrevAndCurrValues(n); // returns a promise
[prev, curr] = [curr, prev + curr];
}
}
// the async service
asyncFetchPrevAndCurrValues = (n) => (
new Promise(res => {
if (n === 1)
[prev, curr] = [undefined, 0];
setTimeout(() => res([prev, curr]), 50);
})
);
// the generator runner
function runFibGen(gen=fibGen(50), args, fibs=[0]) { // generate an array of 50 fibs asynchronously
let item = gen.next(args);
if(!item.done) {
item.value.then(
res => {
fibs = fibs.concat([res[1]]);
/* res contains prev, curr as resolved by the Promise. These will be the basis upon which the generator computes the
next values by using runFibGen to pass them back to the generator with gen.next as follows
*/
runFibGen(gen, res, fibs)
}
);
} else
console.log(fibs);
}
// run it
runFibGen();
// 0112358
// let memo = {
// 0: 0,
// 1: 1
// };
//
// function fib (n) {
//
// if(memo[n] === undefined){
// memo[n] = fib(n-1) + fib(n-2);
// return memo[n]
// }
//
// return memo[n]
// }
//
// console.log(fib(500));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.