Skip to content

Instantly share code, notes, and snippets.

@stelf
Created November 27, 2014 10:36
Show Gist options
  • Save stelf/0a368a029f046a4e0b6c to your computer and use it in GitHub Desktop.
Save stelf/0a368a029f046a4e0b6c to your computer and use it in GitHub Desktop.
infinite stream in JS
// Infite stream implementation with Basic promises.
// inspired by
// http://perl.plover.com/Stream/stream.html#streams
var Stream = function(_head, _tail) {
this.h = _head;
this.t = _tail;
};
Stream.prototype.head = function() {
return this.h;
}
Stream.prototype.tail = function() {
var _tail = this.t;
if (_tail instanceof Function) {
console.log('call tail promise');
this.t = _tail();
}
return this.t;
}
Stream.prototype.show = function(len) {
var cpos = 0;
var self = this;
do {
console.log('element', cpos, ':', self.head());
self = self.tail();
cpos++;
} while(cpos < len);
}
// --- code now ---
function tabulate (f, n) {
console.log('instance of new Stream...');
return new Stream(
f(n), function() {
return tabulate(f, n + 1);
}
);
}
var square = function(a) {
return a * a;
}
console.log('tabulate...');
squares = new tabulate(square, 1);
console.log('show stream...');
squares.show(5);
squares.show(3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment