| 11 | */ |
| 12 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 13 | export function throttle<T extends (...rest: any[]) => any>( |
| 14 | fn: T, |
| 15 | maxCount: number, |
| 16 | durationSeconds: number, |
| 17 | ): (...rest: Parameters<T>) => ReturnType<T> | typeof THROTTLED | typeof SKIPPED { |
| 18 | const counter = new Map<number, number>(); |
| 19 | |
| 20 | const _cleanup = (now: number): void => { |
| 21 | const threshold = now - durationSeconds; |
| 22 | counter.forEach((_value, key) => { |
| 23 | if (key < threshold) { |
| 24 | counter.delete(key); |
| 25 | } |
| 26 | }); |
| 27 | }; |
| 28 | |
| 29 | const _getTotalCount = (): number => { |
| 30 | return [...counter.values()].reduce((a, b) => a + b, 0); |
| 31 | }; |
| 32 | |
| 33 | let isThrottled = false; |
| 34 | |
| 35 | return (...rest: Parameters<T>): ReturnType<T> | typeof THROTTLED | typeof SKIPPED => { |
| 36 | // Date in second-precision, which we use as basis for the throttling |
| 37 | const now = Math.floor(Date.now() / 1000); |
| 38 | |
| 39 | // First, make sure to delete any old entries |
| 40 | _cleanup(now); |
| 41 | |
| 42 | // If already over limit, do nothing |
| 43 | if (_getTotalCount() >= maxCount) { |
| 44 | const wasThrottled = isThrottled; |
| 45 | isThrottled = true; |
| 46 | return wasThrottled ? SKIPPED : THROTTLED; |
| 47 | } |
| 48 | |
| 49 | isThrottled = false; |
| 50 | const count = counter.get(now) || 0; |
| 51 | counter.set(now, count + 1); |
| 52 | |
| 53 | return fn(...rest); |
| 54 | }; |
| 55 | } |