Skip to content

Instantly share code, notes, and snippets.

@ivan-demchenko
Created September 20, 2015 16:27
Show Gist options
  • Save ivan-demchenko/4be1038bf95214a011d4 to your computer and use it in GitHub Desktop.
Save ivan-demchenko/4be1038bf95214a011d4 to your computer and use it in GitHub Desktop.
Lazy list comprehension using generator
// Inspired by Haskell's `takeWhile (<10000) $ map (^3) [1..]`
let nextVal = (x) => x.next().value;
function* mList(x = 0) {
while(1) yield x++;
}
function* map(fn, list) {
while(1) {
yield fn(nextVal(list));
}
}
function* takeWhile(p, list) {
let nv = nextVal(list);
while (p(nv)) {
yield nv;
nv = nextVal(list);
}
}
let tripple = (x) => x * x * x;
let lessThan = (x) => (y) => y < x
let trippledValuesLessThen100 = takeWhile(lessThan(100), map(tripple, mList(1)));
let res = [for (x of trippledValuesLessThen100) x];
console.log(res); // [1,8,27,64]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment