1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483 |
x24
x24
x140
x140
x140
x140
x140
x140
x5
x5
x5
x135
x135
x135
x140
x140
x17
x5
x5
x5
x5
x5
x12
x17
x1
x1
x1
x17
x1
x1
x1
x10
x17
x25
x25
x4
x4
x4
x21
x21
x21
x6
x17
x140
x194
x4
x4
x4
x190
x190
x190
x194
x140
x171
x4
x4
x4
x167
x171
x6
x6
x6
x6
x6
x6
x161
x169
x167
x167
x167
x167
x161
x161
x171
x140
x13
x13
x140
x114
x114
x140
x8
x8
x140
x21
x21
x21
x16
x21
x140
x25
x25
x25
x25
x140
x12
x12
x12
x12
x12
x12
x12
x12
x12
x12
x140
x5
x5
x140
x30
x30
x92
x92
x30
x24
x24 |
I
|
// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.
/**
* A serializable snapshot of a {@linkcode RollingCounter}'s state.
*
* Obtain one via {@linkcode RollingCounter.prototype.toJSON | `toJSON`} and
* restore it with {@linkcode RollingCounter.from}.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*/
export interface RollingCounterSnapshot {
/** Segment counts ordered from oldest to newest. */
readonly segments: readonly number[];
}
/**
* A fixed-size rolling counter.
*
* The counter splits a window into a fixed number of segments, each tracking
* a count. It has no built-in clock. Call
* {@linkcode RollingCounter.prototype.rotate | `rotate`} to advance the
* window on your own schedule.
*
* The class is iterable and yields segment counts from oldest to newest.
*
* | Method | Time complexity |
* | ----------------- | -------------------------------------- |
* | increment(n) | Constant |
* | rotate(steps) | Linear in min(steps, segment count) |
* | current | Constant |
* | total | Constant |
* | segmentCount | Constant |
* | at(index) | Constant |
* | clear() | Linear in the number of segments |
* | toArray() | Linear in the number of segments |
* | toJSON() | Linear in the number of segments |
* | [Symbol.iterator] | Linear in the number of segments |
* | RollingCounter() | Linear in the number of segments |
* | RollingCounter.from(snapshot) | Linear in the number of segments |
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @example Usage
* ```ts
* import { RollingCounter } from "@std/data-structures/unstable-rolling-counter";
* import { assertEquals } from "@std/assert";
*
* // 3 segments, all starting at zero
* const counter = new RollingCounter(3);
*
* // Add 5 to the current (newest) segment
* counter.increment(5);
* assertEquals(counter.total, 5);
* assertEquals([...counter], [0, 0, 5]);
*
* // Advance the window, then add 3 to the new segment
* counter.rotate();
* counter.increment(3);
* assertEquals(counter.total, 8);
* assertEquals([...counter], [0, 5, 3]);
*
* // Bulk-rotate 2 steps: evicts the two oldest (0 and 5)
* counter.rotate(2);
* assertEquals(counter.total, 3);
* assertEquals([...counter], [3, 0, 0]);
* ```
*/
export class RollingCounter implements Iterable<number> {
#segments: number[];
#cursor: number;
#total: number;
/**
* Creates a counter with the given number of segments, all starting at zero.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @param segmentCount The number of segments. Must be a positive integer.
*/
constructor(segmentCount: number) {
if (
!Number.isInteger(segmentCount) || segmentCount < 1
) {
throw new RangeError(
`Cannot create RollingCounter: segmentCount must be a positive integer, got ${segmentCount}`,
);
}
this.#segments = new Array<number>(segmentCount).fill(0);
this.#cursor = segmentCount - 1;
this.#total = 0;
}
/**
* Creates a counter from a snapshot previously obtained via
* {@linkcode RollingCounter.prototype.toJSON | `toJSON`}. The snapshot's
* `segments` array defines both the number of segments and their initial
* values, ordered oldest to newest (matching iteration order). The last
* element is the current (newest) segment.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @param snapshot A snapshot previously obtained from `toJSON`.
* @returns A new `RollingCounter` with the given state.
*
* @example Round-trip serialization
* ```ts
* import { RollingCounter } from "@std/data-structures/unstable-rolling-counter";
* import { assertEquals } from "@std/assert";
*
* const original = new RollingCounter(3);
* original.increment(5);
* original.rotate();
* original.increment(3);
*
* const snapshot = original.toJSON();
* const restored = RollingCounter.from(snapshot);
*
* assertEquals([...restored], [...original]);
* assertEquals(restored.total, original.total);
* assertEquals(restored.segmentCount, original.segmentCount);
* ```
*/
static from(snapshot: RollingCounterSnapshot): RollingCounter {
if (snapshot === null || typeof snapshot !== "object") {
throw new TypeError(
`Cannot restore RollingCounter: "snapshot" must be an object, got ${
snapshot === null ? "null" : typeof snapshot
}`,
);
}
const { segments } = snapshot;
if (!Array.isArray(segments)) {
throw new TypeError(
`Cannot restore RollingCounter: "segments" must be an array, got ${typeof segments}`,
);
}
if (segments.length < 1) {
throw new RangeError(
'Cannot restore RollingCounter: "segments" must be a non-empty array',
);
}
const counter = new RollingCounter(segments.length);
for (let i = 0; i < segments.length; i++) {
const v = segments[i]!;
if (!Number.isInteger(v) || v < 0) {
throw new RangeError(
`Cannot restore RollingCounter: segment[${i}] must be a non-negative integer, got ${v}`,
);
}
counter.#segments[i] = v;
counter.#total += v;
}
return counter;
}
/**
* Adds `n` to the current segment.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @param n The amount to add. Defaults to `1`. Must be a non-negative integer.
* @returns The new total across all segments.
*
* @example Usage
* ```ts
* import { RollingCounter } from "@std/data-structures/unstable-rolling-counter";
* import { assertEquals } from "@std/assert";
*
* const counter = new RollingCounter(3);
* const total = counter.increment(5);
* assertEquals(total, 5);
* ```
*/
increment(n: number = 1): number {
if (!Number.isInteger(n) || n < 0) {
throw new RangeError(
`Cannot increment RollingCounter: n must be a non-negative integer, got ${n}`,
);
}
this.#segments[this.#cursor]! += n;
this.#total += n;
return this.#total;
}
/**
* Advances the window by `steps`, dropping the oldest segments. If `steps`
* is at least {@linkcode segmentCount}, all segments are cleared.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @param steps How many steps to advance. Defaults to `1`. Must be a
* non-negative integer.
* @returns The sum of the counts that were removed.
*
* @example Usage
* ```ts
* import { RollingCounter } from "@std/data-structures/unstable-rolling-counter";
* import { assertEquals } from "@std/assert";
*
* const counter = new RollingCounter(2);
* counter.increment(10);
* counter.rotate();
* const evicted = counter.rotate();
* assertEquals(evicted, 10);
* ```
*
* @example Bulk rotation
* ```ts
* import { RollingCounter } from "@std/data-structures/unstable-rolling-counter";
* import { assertEquals } from "@std/assert";
*
* const counter = new RollingCounter(3);
* counter.increment(5);
* counter.rotate();
* counter.increment(3);
*
* const evicted = counter.rotate(2);
* assertEquals(evicted, 5);
* assertEquals(counter.total, 3);
* ```
*/
rotate(steps: number = 1): number {
if (!Number.isInteger(steps) || steps < 0) {
throw new RangeError(
`Cannot rotate RollingCounter: steps must be a non-negative integer, got ${steps}`,
);
}
const len = this.#segments.length;
if (steps >= len) {
const evicted = this.#total;
this.#segments.fill(0);
this.#cursor = (this.#cursor + steps) % len;
this.#total = 0;
return evicted;
}
let evicted = 0;
for (let i = 0; i < steps; i++) {
this.#cursor = (this.#cursor + 1) % len;
evicted += this.#segments[this.#cursor]!;
this.#segments[this.#cursor] = 0;
}
this.#total -= evicted;
return evicted;
}
/**
* The count in the current (newest) segment.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @returns The count in the current segment.
*
* @example Usage
* ```ts
* import { RollingCounter } from "@std/data-structures/unstable-rolling-counter";
* import { assertEquals } from "@std/assert";
*
* const counter = new RollingCounter(3);
* counter.increment(5);
* assertEquals(counter.current, 5);
*
* counter.rotate();
* assertEquals(counter.current, 0);
*
* counter.increment(3);
* assertEquals(counter.current, 3);
* ```
*/
get current(): number {
return this.#segments[this.#cursor]!;
}
/**
* The sum of all segment counts.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @returns The sum of all segment counts.
*
* @example Usage
* ```ts
* import { RollingCounter } from "@std/data-structures/unstable-rolling-counter";
* import { assertEquals } from "@std/assert";
*
* const counter = new RollingCounter(3);
* counter.increment(5);
* counter.rotate();
* counter.increment(3);
* assertEquals(counter.total, 8);
* ```
*/
get total(): number {
return this.#total;
}
/**
* The number of segments in the window.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @returns The number of segments.
*
* @example Usage
* ```ts
* import { RollingCounter } from "@std/data-structures/unstable-rolling-counter";
* import { assertEquals } from "@std/assert";
*
* const counter = new RollingCounter(5);
* assertEquals(counter.segmentCount, 5);
* ```
*/
get segmentCount(): number {
return this.#segments.length;
}
/**
* Returns the segment count at `index`, where index `0` is the oldest
* segment and index `segmentCount - 1` is the current (newest) segment.
* Negative indices count from the newest end (`at(-1)` is the current
* segment, same as {@linkcode RollingCounter.prototype.current | current}).
* Returns `undefined` for out-of-range indices.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @param index The zero-based index in oldest-to-newest order. Negative
* values count from the newest end.
* @returns The count at the index, or `undefined` if out of range.
*
* @example Usage
* ```ts
* import { RollingCounter } from "@std/data-structures/unstable-rolling-counter";
* import { assertEquals } from "@std/assert";
*
* const counter = new RollingCounter(3);
* counter.increment(5);
* counter.rotate();
* counter.increment(3);
*
* assertEquals(counter.at(0), 0);
* assertEquals(counter.at(1), 5);
* assertEquals(counter.at(2), 3);
* assertEquals(counter.at(-1), 3);
* assertEquals(counter.at(99), undefined);
* ```
*/
at(index: number): number | undefined {
const len = this.#segments.length;
if (index < 0) index += len;
if (index < 0 || index >= len) return undefined;
return this.#segments[(this.#cursor + 1 + index) % len]!;
}
/**
* Resets all segments to zero, as if the counter were just created.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @example Usage
* ```ts
* import { RollingCounter } from "@std/data-structures/unstable-rolling-counter";
* import { assertEquals } from "@std/assert";
*
* const counter = new RollingCounter(3);
* counter.increment(10);
* counter.clear();
* assertEquals(counter.total, 0);
* ```
*/
clear(): void {
this.#segments.fill(0);
this.#cursor = this.#segments.length - 1;
this.#total = 0;
}
/**
* Returns a fresh array of segment counts ordered from oldest to newest
* (matching iteration order). The returned array is owned by the caller;
* mutating it does not affect the counter.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @returns A new array of segment counts in oldest-to-newest order.
*
* @example Usage
* ```ts
* import { RollingCounter } from "@std/data-structures/unstable-rolling-counter";
* import { assertEquals } from "@std/assert";
*
* const counter = new RollingCounter(3);
* counter.increment(5);
* counter.rotate();
* counter.increment(3);
*
* assertEquals(counter.toArray(), [0, 5, 3]);
* ```
*/
toArray(): number[] {
const segs = this.#segments;
const len = segs.length;
let start = this.#cursor + 1;
if (start >= len) start = 0;
const result = new Array<number>(len);
const firstLen = len - start;
for (let i = 0; i < firstLen; i++) result[i] = segs[start + i]!;
for (let i = 0; i < start; i++) result[firstLen + i] = segs[i]!;
return result;
}
/**
* Returns a serializable snapshot of the counter state. The `segments`
* array is ordered oldest to newest (matching iteration order), so the
* last element is the current segment.
*
* The snapshot is compatible with `JSON.stringify` and can be restored
* with {@linkcode RollingCounter.from}.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @returns A plain-object snapshot of the counter.
*
* @example JSON round-trip
* ```ts
* import { RollingCounter } from "@std/data-structures/unstable-rolling-counter";
* import { assertEquals } from "@std/assert";
*
* const counter = new RollingCounter(3);
* counter.increment(5);
*
* const json = JSON.stringify(counter);
* const restored = RollingCounter.from(JSON.parse(json));
* assertEquals(restored.total, 5);
* ```
*/
toJSON(): RollingCounterSnapshot {
return { segments: this.toArray() };
}
/**
* Yields segment counts from oldest to newest.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @returns An iterator over segment counts.
*
* @example Usage
* ```ts
* import { RollingCounter } from "@std/data-structures/unstable-rolling-counter";
* import { assertEquals } from "@std/assert";
*
* const counter = new RollingCounter(3);
* counter.increment(5);
* counter.rotate();
* counter.increment(3);
* assertEquals([...counter], [0, 5, 3]);
* ```
*/
*[Symbol.iterator](): IterableIterator<number> {
const len = this.#segments.length;
for (let i = 1; i <= len; i++) {
yield this.#segments[(this.#cursor + i) % len]!;
}
}
/**
* A string tag for the class, used by `Object.prototype.toString()`.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @example Usage
* ```ts
* import { RollingCounter } from "@std/data-structures/unstable-rolling-counter";
* import { assertEquals } from "@std/assert";
*
* const counter = new RollingCounter(3);
* assertEquals(
* Object.prototype.toString.call(counter),
* "[object RollingCounter]",
* );
* ```
*/
readonly [Symbol.toStringTag] = "RollingCounter" as const;
}
|