Created
October 17, 2019 19:35
-
-
Save Floofies/7b8ddc2ab0c99b21b31fe3bc0258975f to your computer and use it in GitHub Desktop.
Channel Prototype
This file contains hidden or 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
function Channel(limit = 0) { | |
this.limit = limit; | |
this.buffer = []; | |
this.readers = []; | |
this.wakeRead = null; | |
this.wakeWrite = null; | |
this.readPromise = null; | |
this.writePromise = null; | |
} | |
Channel.prototype.waitForRead = function() { | |
if (this.readPromise === null) { | |
this.readPromise = new Promise(resolve => { | |
this.wakeRead = resolve; | |
}); | |
} | |
return this.readPromise; | |
}; | |
Channel.prototype.waitForWrite = function() { | |
if (this.writePromise === null) { | |
this.writePromise = new Promise(resolve => { | |
this.wakeWrite = resolve; | |
}); | |
} | |
return this.writePromise; | |
}; | |
Channel.prototype.read = async function(wait = true) { | |
if (this.wakeWrite !== null) { | |
this.wakeWrite(); | |
this.wakeWrite = null; | |
} | |
if (this.buffer.length === 0) { | |
if (wait) await this.waitForWrite(); | |
else return null; | |
} | |
return this.buffer.unshift(); | |
}; | |
Channel.prototype.write = async function(data, wait = true) { | |
if (this.wakeRead !== null) { | |
this.wakeRead(); | |
this.wakeRead = null; | |
} | |
if (wait && this.readers.length === 0) await this.waitForWrite(); | |
this.buffer.push(data); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment