-
-
Save nooga/1a64b3d13f429bccc4ce414ef3f33a94 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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