Skip to content

Instantly share code, notes, and snippets.

@VivienAdnot
Created January 15, 2016 09:20
Show Gist options
  • Save VivienAdnot/83fa09e2bb7e5410d949 to your computer and use it in GitHub Desktop.
Save VivienAdnot/83fa09e2bb7e5410d949 to your computer and use it in GitHub Desktop.
stream head tail
function node(head, tail) {
return [head, tail];
};
function head(stream) {
return stream[0];
};
function tail(stream) {
var tail = stream[stream.length - 1];
return (tail instanceof Function) ? tail() : tail;
};
function drop(stream) {
var h = head(stream);
var t = tail(stream);
stream[0] = t ? t[0] : null;
stream[1] = t ? t[1] : null;
return h;
};
function iterate(stream, callback, limit) {
while (head(stream) && ((undefined == limit) || (limit > 0))) {
limit && limit--;
callback(drop(stream));
};
};
function show(stream, limit) {
iterate(stream, function (x) {
console.log(x);
}, limit);
};
//Examples
function upto(from, to) {
return (from > to) ? null : node(from, function() {
return upto(from + 1, to);
});
};
function upfrom(start) {
return node(start, function() {
return upfrom(start + 1);
});
};
console.log("upto:");
show(upto(3, 6));
console.log("upfrom:");
show(upfrom(7), 10);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment