Skip to content

Instantly share code, notes, and snippets.

@PetKatt
Last active October 9, 2018 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PetKatt/bdcaa04e68edd457f8f2d0e75a262d44 to your computer and use it in GitHub Desktop.
Save PetKatt/bdcaa04e68edd457f8f2d0e75a262d44 to your computer and use it in GitHub Desktop.
Lazy Evaluation in javascript by memoized version of call-by-name method
// EAGER EVALUATION with RangeError on the var stream
function Stream(value) {
this.value = value;
this.next = new Stream(value + 1);
}
var stream = new Stream(10);
console.log(stream);
// LAZY EVALUATION
function Stream(value) {
this.value = value;
Object.defineProperty(this, "next", {
get : function() {
return new Stream(this.value + 1);
}
});
}
Stream.prototype.takeUntil = function(n, accumulator) {
accumulator = accumulator || [];
if (n < this.value) {
return;
}
if (n === this.value) {
return accumulator;
}
accumulator.push(this.value);
return this.next.takeUntil(n, accumulator);
}
var stream = new Stream(10);
console.log(stream.takeUntil(20));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment