Skip to content

Instantly share code, notes, and snippets.

@chenglou
Last active February 18, 2022 04:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chenglou/5689382 to your computer and use it in GitHub Desktop.
Save chenglou/5689382 to your computer and use it in GitHub Desktop.
JavaScript generators: fibonacci, natural numbers and sieve of Erasthosthenes for primes.
/* Infinite stream of numbers!
Format: `[number, suspendedStream]` where suspendedStream is really just a
function that, upon calling, returns another `[number, suspendedStream]`.
*/
function head(a) {
return a[0];
}
function tail(a) {
return a[1]();
}
function take(n, a) {
if (n === 0) return [];
return [head(a)].concat(take(n - 1, tail(a)));
}
function fib(a, b) {
return [a, function() { return fib(b, a + b); }];
}
function one() {
return [1, function() { return one(); }];
}
function nat(a) {
return [a, function() { return nat(a + 1); }];
}
function filter(a, fn) {
if (fn(head(a))) {
return [head(a), function() { return filter(tail(a), fn); }];
} else {
return filter(tail(a), fn);
}
}
function sieve(a) {
var x = head(a);
var discarder = function(item) { return item % x !== 0; };
return [x, function() {
return sieve(filter(tail(a), discarder));
}];
}
console.log(take(10, one())); // [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ].
console.log(take(10, fib(0, 1))); // [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ].
console.log(take(10, sieve(nat(2)))); // [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment