Skip to content

Instantly share code, notes, and snippets.

@moleike
Forked from kana/lazy.js
Created April 8, 2016 09:21
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 moleike/0e14bd5813d178a73d380faed89d0794 to your computer and use it in GitHub Desktop.
Save moleike/0e14bd5813d178a73d380faed89d0794 to your computer and use it in GitHub Desktop.
Lazy evaluation in JavaScript
function delay(expressionAsFunction) {
var result;
var isEvaluated = false;
return function () {
if (!isEvaluated)
result = expressionAsFunction();
return result;
};
}
function force(promise) {
return promise();
}
function cons(car, cdr) {
return [car, cdr];
}
function next(n) {
return cons(n, delay(function () {return next(n + 1);}));
}
function head(stream) {
return stream[0];
}
function tail(stream) {
return force(stream[1]);
}
var stream = next(0);
console.log(stream);
console.log(head(tail(tail(stream)))); //==> 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment