Class: SlideWindowCounter
Package:
@litert/concurrentImport path:@litert/concurrentSource: packages/partials/concurrent/src/Classes/SlideWindowCounter.ts
A counter backed by a sliding time window. The window is divided into windowQty sub-windows of equal duration. Counts in expired sub-windows are automatically discarded when any method is called. The total represents only counts recorded within the current sliding window.
Also implements ICounter, so it can be used directly with CountingRateLimiter and CircuitBreaker.
Constructor
new SlideWindowCounter(options?: ISlideWindowCounterOptions)See ISlideWindowCounterOptions.
Throws:
Error— ifwindowQtyorwindowSizeMsis not a positive safe integer.
Properties
| Property | Type | Description |
|---|---|---|
windowSize | number (readonly) | Total window duration in milliseconds |
windowQty | number (readonly) | Number of sub-windows |
Methods
getTotal()
getTotal(): numberReturns the total count across all active (non-expired) sub-windows.
increase(step?)
increase(step?: number): voidIncrements the count in the current sub-window.
| Parameter | Type | Default | Description |
|---|---|---|---|
step | number? | 1 | Amount to add |
reset()
reset(): voidClears all sub-window data, resetting the total to zero.
getWindows()
getWindows(): ReadonlyArray<{ time: number; count: number }>Returns a snapshot of the current sub-windows, each with a time (start timestamp) and count.
Example
import { SlideWindowCounter } from '@litert/concurrent';
const counter = new SlideWindowCounter({
windowSizeMs: 10_000, // 10-second window
windowQty: 5, // divided into five 2-second sub-windows
});
counter.increase();
counter.increase(3);
console.log(counter.getTotal()); // 4