Skip to content

Instantly share code, notes, and snippets.

@Kamisama666
Created July 30, 2019 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kamisama666/e20193a7f109576e187ef0bd9997d43b to your computer and use it in GitHub Desktop.
Save Kamisama666/e20193a7f109576e187ef0bd9997d43b to your computer and use it in GitHub Desktop.
Listens to an EventEmitter and reduces the data returned.
/*
Listens to an EventEmitter and reduces the data returned. The EventEmitter must at least three types of events:
- dataEvent: it sends the data to be reduced
- endEvent: it signals the completion of the operation
- errorEvent: it sends an error. The operation is interrupted to handle it
*/
function reduceEventEmmitter({dataEvent, endEvent, errorEvent = null}, accumulator = [], reducer, eventEmitter, cb) {
eventEmitter.on(dataEvent, function handleDataEvent(data) {
accumulator = reducer(accumulator, data);
});
eventEmitter.on(endEvent, function handleEndEvent() {
cb(null, accumulator);
});
if (errorEvent) {
eventEmitter.on(errorEvent, function handleEndEvent(error) {
cb(error);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment