Last active
October 9, 2018 14:27
-
-
Save PetKatt/bdcaa04e68edd457f8f2d0e75a262d44 to your computer and use it in GitHub Desktop.
Lazy Evaluation in javascript by memoized version of call-by-name method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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