I usually do not create Streams, but it seems that JavaScript doesn't have a built-in one and I figured I would do it for a personal project I am working on. This code seems to work as intended and does what I want just fine, but I have concerns mainly about how often I am checking my buffer. I am mainly looking for a recommendation about how often I should check to see if any data has been written to my buffer. If there are any other improvements/suggestions, I am open to hearing them!
Edit: After thinking about this more, I realized I could do this as event-driven instead and let the system/browser handle the blocking. I left both functions in so people can weigh in on either one. However, I would still like input on the first approach for general knowledge.
const dataAddedEvent = new Event('stream.data_recieved');
const dataAddedEventTarget = new EventTarget();
const StreamPrototype = {
_data: [],
_callbacks: [],
readAsync: async function* () {
while(await sleep(25)) {
let data;
while((data = this._data.pop()))
yield data;
}
},
onData: function(callback) {
if (callback instanceof Function)
this._callbacks.push(callback);
},
push: function(data) {
if (data) {
this._pushOntoStack(data);
}
},
_pushOntoStack: async function(data) {
return new Promise(resolve => {
this._data.push(data); // Uses Sleeps
this._callbacks.forEach(item => { // Pushes data out using event-driven
item(data);
});
});
}
};
// This was just copied from the internet
const sleep = time => new Promise(res => setTimeout(res, time, "done sleeping"));