Skip to content

Instantly share code, notes, and snippets.

@baetheus
Last active May 26, 2019 20:30
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 baetheus/11d7609e7469b5c48c38eff60abce686 to your computer and use it in GitHub Desktop.
Save baetheus/11d7609e7469b5c48c38eff60abce686 to your computer and use it in GitHub Desktop.
rxjs: maxCountDuringPeriod
/**
* 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