Skip to content

Instantly share code, notes, and snippets.

@AutoSponge
Last active October 17, 2015 01:19
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 AutoSponge/24acb09d3f24739f919d to your computer and use it in GitHub Desktop.
Save AutoSponge/24acb09d3f24739f919d to your computer and use it in GitHub Desktop.
composing lazy evaluation functions
function* random(limit = 4) {
let count = 0
while(count < limit) {
yield Math.random();
count++;
}
}
function* map(f, gen){
let next;
let result = gen.next();
while(!result.done){
next = yield f(result.value)
result = gen.next();
}
return result.value
}
const toFixed = n => +n.toFixed(2);
const add1 = n => +n + 1;
const log = console.log.bind(console);
// const x = map(log, map(toFixed, map(add1, random())));
// [...x];
//const compose = (...f) => seed => f.reduce((gx, fn) => (map(fn, gx)), seed);
// const x = compose(add1, toFixed);
// console.log([...x(random(4))]);
// const pipe = (...f) => seed => f.reduceRight((gx, fn) => (map(fn, gx)), seed)
// const x = pipe(toFixed, add1);
// console.log([...x(random(4))]);
function* reduce(gen, f) {
let next;
let result = gen.next();
while(!result.done){
next = yield f(result.value)
result = gen.next();
}
return result.value
}
const compose = (...f) => seed => f.reduce(reduce, seed);
const pipe = (...f) => seed => f.reduceRight(reduce, seed);
console.log([...x(random(4))]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment