Skip to content

Instantly share code, notes, and snippets.

@Olical
Created May 22, 2015 09:26
Show Gist options
  • Select an option

  • Save Olical/75b435fce2091f79155e to your computer and use it in GitHub Desktop.

Select an option

Save Olical/75b435fce2091f79155e to your computer and use it in GitHub Desktop.
Some experiments with lazy arrays in JavaScript inspired by Clojure's lazy-seq
function LazyValue(fn) {
this.valueOf = fn;
}
function lazyArray(fn) {
return [new LazyValue(fn)];
}
function cons(item, arr) {
return [item].concat(arr);
}
function first(arr) {
var v = arr[0].valueOf();
return v[1] instanceof LazyValue ? v[0] : v;
}
function rest(arr) {
return arr[1].valueOf();
}
// Should also be lazy really.
function take(n, arr) {
return n - 1 > 0 ? cons(first(arr), take(n - 1, rest(arr))) : arr.slice(0, -1);
}
function positiveNumbers(n) {
return cons(n, lazyArray(function () {
return positiveNumbers(n + 1);
}));
}
first(rest(rest(positiveNumbers(10)))); // 12
take(5, positiveNumbers(1)); // [1, 2, 3, 4, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment