Created
March 1, 2019 00:05
Star
You must be signed in to star a gist
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