Created
July 30, 2019 09:55
-
-
Save Kamisama666/e20193a7f109576e187ef0bd9997d43b to your computer and use it in GitHub Desktop.
Listens to an EventEmitter and reduces the data returned.
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
/* | |
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