Skip to content

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

ts
new SlideWindowCounter(options?: ISlideWindowCounterOptions)

See ISlideWindowCounterOptions.

Throws:

  • Error — if windowQty or windowSizeMs is not a positive safe integer.

Properties

PropertyTypeDescription
windowSizenumber (readonly)Total window duration in milliseconds
windowQtynumber (readonly)Number of sub-windows

Methods

getTotal()

ts
getTotal(): number

Returns the total count across all active (non-expired) sub-windows.


increase(step?)

ts
increase(step?: number): void

Increments the count in the current sub-window.

ParameterTypeDefaultDescription
stepnumber?1Amount to add

reset()

ts
reset(): void

Clears all sub-window data, resetting the total to zero.


getWindows()

ts
getWindows(): ReadonlyArray<{ time: number; count: number }>

Returns a snapshot of the current sub-windows, each with a time (start timestamp) and count.


Example

ts
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