Last active
May 26, 2019 20:30
-
-
Save baetheus/11d7609e7469b5c48c38eff60abce686 to your computer and use it in GitHub Desktop.
rxjs: maxCountDuringPeriod
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
/** | |
* maxCountDuringPeriod | |
*/ | |
export const maxCountDuringPeriod = (count: number, period: number) => (obs: Observable<any>) => { | |
if (count < 2) { | |
throw new Error('maxCountDuringPeriod count must be greater than or equal to 2'); | |
} | |
if (period < 0) { | |
throw new Error('maxCountDuringPeriod period must be positive'); | |
} | |
return obs.pipe( | |
map(_ => currentUnixTime()), | |
bufferCount(count, 1), // Emit arrays of unix time (by event) | |
filter(xs => xs.length === count), // Filter out buffers that don't exceed count restriction | |
map(xs => xs[xs.length - 1] - xs[0]), // Map to seconds between first and last event | |
filter(x => x <= period), // Filter out groupings that occur outside of the period restraint | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment