Created
March 1, 2019 00:05
-
-
Save artisonian/d0ce22af048ea20d144b9e2427b57e7e 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
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