Skip to content

Instantly share code, notes, and snippets.

@nooga

nooga/chan.js Secret

Created September 10, 2018 21:11
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 nooga/1a64b3d13f429bccc4ce414ef3f33a94 to your computer and use it in GitHub Desktop.
Save nooga/1a64b3d13f429bccc4ce414ef3f33a94 to your computer and use it in GitHub Desktop.
class Chan {
constructor() {
this.waiting = 0;
this.reads = [];
this.available = 0;
this.buffer = [];
this.closed = false;
}
[Symbol.asyncIterator]() {
return this
// {
// next: () => this.next()
// }
}
put(value) {
if(this.closed) {
console.log("Can't write to a closed channel");
return;
}
if(this.waiting > 0) {
const r = this.reads.shift();
this.waiting--;
r({value, done: false});
} else {
this.available++;
this.buffer.push(value);
}
}
next() {
if(this.available > 0) {
this.available--;
const value = this.buffer.shift();
return new Promise(r => r({ value, done: false}));
} else {
this.waiting++;
var that = this;
const p = new Promise(function(r) {
that.reads.push(r);
});
return p;
}
}
}
const c = new Chan();
(async () => {
console.log("1", await c.next())
console.log("2", await c.next())
console.log("3", await c.next())
console.log("4", await c.next())
console.log("5", await c.next())
console.log("end");
})();
(async () => {
c.put(1);
c.put(2);
c.put(3);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment