Skip to content

Instantly share code, notes, and snippets.

@tantalor tantalor/go.js
Created Oct 10, 2011

Embed
What would you like to do?
Prime sieve in Go-flavored JavaScript
#!/usr/bin/env node
var sys = require('sys');
function go (fn) {
setTimeout(fn, 0);
};
var chan = function () {
this.readers = []; // [cb, ...]
this.writers = []; // [[value, cb], ...]
};
chan.prototype.read = function (cb) {
if (this.writers.length) {
// consume a writer
var writer = this.writers.shift();
cb(writer[0]);
writer[1](writer[0]);
} else {
// queue the reader
this.readers.push(cb);
}
};
chan.prototype.write = function (value, cb) {
if (this.readers.length) {
// consumer a reader
var reader = this.readers.shift();
reader(value);
cb(value);
} else {
// queue the writer
this.writers.push([value, cb]);
}
};
function integers () {
var ch = new chan();
go(function () {
var producer = function (i) {
ch.write(i + 1, producer);
};
ch.write(2, producer);
});
return ch;
};
function filter_multiples (ch, prime) {
var out = new chan();
go(function () {
var consumer = function (i) {
if (i % prime != 0) {
out.write(i, function () {
ch.read(consumer);
});
} else {
ch.read(consumer);
}
};
ch.read(consumer);
});
return out;
};
function sieve () {
var out = new chan();
go(function () {
var ch = integers();
function iteration () {
ch.read(function (prime) {
out.write(prime, function () {
ch = filter_multiples(ch, prime);
iteration();
});
});
};
iteration();
});
return out;
};
function main () {
var primes = sieve();
function iteration() {
primes.read(function (i) {
sys.puts(i);
iteration();
});
};
iteration();
}
main();
$ ./go.js
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.