Skip to content

Instantly share code, notes, and snippets.

@mgtitimoli
Last active July 22, 2016 20:10
Show Gist options
  • Save mgtitimoli/2e37f7cea7c8d05ae2faeff5192fa9d5 to your computer and use it in GitHub Desktop.
Save mgtitimoli/2e37f7cea7c8d05ae2faeff5192fa9d5 to your computer and use it in GitHub Desktop.
reduce-until & iteration-context & generator-to-array & fibonacci-generator
export default function* fibonacciGenerator() {
let prev = 1;
let cur = 1;
yield prev;
while(true) {
yield cur;
[prev, cur] = [cur, prev + cur];
}
}
import * as iterationContext from "./iteration-context";
import reduceUntil from "./reduce-until";
export default function generatorToArray(gen, limit) {
let iteContext = iterationContext.create(gen);
return reduceUntil(
Array.from({length: limit}),
result => {
iteContext = iterationContext.next(iteContext);
result.push(iteContext.status.value);
return result;
},
() => iteContext.status.done,
[]
);
}
function create(generator) {
const iterator = generator();
return {
iterator,
status: undefined
},
}
function next({iterator}) {
return {
iterator,
status: iterator.next()
};
}
export {
create,
next
};
import generatorToArray from "./generator-to-array";
import fibonacciGenerator from "./fibonacci-generator";
generatorToArray(fibonacciGenerator, 10); // [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
export default function reduceUntil(arr, reduce, done, seed) {
let result = seed;
arr.some((elem, i) => {
result = reduce(result, elem, i);
return done(result);
});
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment