Skip to content

Instantly share code, notes, and snippets.

@efrence
Last active July 12, 2016 04:10
Show Gist options
  • Save efrence/13ec6da93c8b7be6707e08347dbe3716 to your computer and use it in GitHub Desktop.
Save efrence/13ec6da93c8b7be6707e08347dbe3716 to your computer and use it in GitHub Desktop.
Lazy comprehention
function take(n, str) {
function _take(n, str, accum) {
if (n === 0) {
return accum;
}
const { value, next } = str();
return _take(n - 1, next, accum.concat(value));
}
return _take(n, str, []);
}
function stream(fn, initial) {
function _stream(value) {
return {
value,
next() {
return _stream(fn(value));
}
};
}
return () => _stream(initial);
}
function smap(fn, originalStr) {
function _stream(str) {
const { value, next } = str();
return {
value: fn(value),
next() {
return _stream(next);
}
};
}
return () => _stream(originalStr);
}
function sfilter(fn, originalStr) {
function _stream(str) {
const { value, next } = str();
if (fn(value)) {
return {
value,
next() {
return _stream(next);
}
};
}
return _stream(next);
}
return () => _stream(originalStr);
}
function lazyComprehention(map_fn,str,filter_fn){
return smap(map_fn,sfilter(filter_fn,str));
}
const nats = stream(n => n + 1, 1);
squared_odd_numbers = lazyComprehention(n => n * n, nats, n => n % 2 !== 0)
console.log(take(10,squared_odd_numbers)); // [1, 9, 25, 49, 81, 121, 169, 225, 289, 361]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment