Created
June 21, 2018 07:27
-
-
Save gsrai/708df5eca06bc39be107006d5401731f to your computer and use it in GitHub Desktop.
Lazy evaluation in javascript, with a simple stream implementation because we can
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
// Lazy evaluation in javascript | |
// call by name: lazily evaluate the arguments passed into the function | |
// call by value: eagerly evaluate the arguments passed into the function | |
// call by need: memoized version of call by name | |
// memoization: avoid recomputation for the same inputs by caching the results | |
// | |
// Javascript by default uses call by value, however by using Object.defineProperty(), | |
// lazy evaluation in javascript object properties can be performed | |
// | |
// e.g. an infinite data structure - the stream, can only exist with lazy evaluation (else infinite recursion) | |
function Stream(value) { | |
this.value = value | |
Object.defineProperty(this, 'next', { | |
get: () => new Stream(value + 1) | |
}) | |
} | |
Stream.prototype.takeUntil = function (n, acc) { | |
const _acc = acc || [] | |
if (n < this.value) { return } | |
if (n === this.value) { return _acc } | |
_acc.push(this.value) | |
return this.next.takeUntil(n, _acc) | |
} | |
function main() { | |
const stream = new Stream(10) | |
console.log(stream.takeUntil(20)) | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment