Skip to content

Instantly share code, notes, and snippets.

@artisonian
Created March 1, 2019 00:05
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save artisonian/d0ce22af048ea20d144b9e2427b57e7e to your computer and use it in GitHub Desktop.
main().catch(console.error);
async function main() {
const clicks = streamify(document, "click");
let clickCount = 0;
for await (const event of clicks) {
console.log("click", event, clickCount);
if (clickCount++ > 2) {
clicks.return();
}
}
console.log("bye");
}
function streamify(element, event) {
const pushQueue = [];
const pullQueue = [];
let done = false;
function pushValue(event) {
if (pullQueue.length !== 0) {
pullQueue.shift()({ value: event, done: false });
} else {
pushQueue.push(event);
}
}
function pullValue() {
return new Promise(resolve => {
if (pushQueue.length !== 0) {
resolve({ value: pushQueue.shift(), done: false });
} else {
pullQueue.push(resolve);
}
});
}
element.addEventListener(event, pushValue);
return {
[Symbol.asyncIterator]() {
return this;
},
next() {
return done ? this.return() : pullValue();
},
return() {
done = true;
element.removeEventListener(event, pushValue);
return Promise.resolve({ value: undefined, done });
},
throw(error) {
done = true;
return Promise.reject(error);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment