Skip to content

Instantly share code, notes, and snippets.

@johnmutuma5
Last active August 26, 2018 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnmutuma5/86f0fb0d1df51dcf2f566d737002ada0 to your computer and use it in GitHub Desktop.
Save johnmutuma5/86f0fb0d1df51dcf2f566d737002ada0 to your computer and use it in GitHub Desktop.
// 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