Last active
July 22, 2016 20:10
-
-
Save mgtitimoli/2e37f7cea7c8d05ae2faeff5192fa9d5 to your computer and use it in GitHub Desktop.
reduce-until & iteration-context & generator-to-array & fibonacci-generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function* fibonacciGenerator() { | |
let prev = 1; | |
let cur = 1; | |
yield prev; | |
while(true) { | |
yield cur; | |
[prev, cur] = [cur, prev + cur]; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
[] | |
); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function create(generator) { | |
const iterator = generator(); | |
return { | |
iterator, | |
status: undefined | |
}, | |
} | |
function next({iterator}) { | |
return { | |
iterator, | |
status: iterator.next() | |
}; | |
} | |
export { | |
create, | |
next | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import generatorToArray from "./generator-to-array"; | |
import fibonacciGenerator from "./fibonacci-generator"; | |
generatorToArray(fibonacciGenerator, 10); // [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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