Last active
October 17, 2015 01:19
-
-
Save AutoSponge/24acb09d3f24739f919d to your computer and use it in GitHub Desktop.
composing lazy evaluation functions
This file contains 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* 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