MCPcopy Create free account
hub / github.com/garrytan/gstack / CircularBuffer

Class CircularBuffer

browse/src/buffers.ts:20–89  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

18// ─── CircularBuffer ─────────────────────────────────────────
19
20export class CircularBuffer<T> {
21 private buffer: (T | undefined)[];
22 private head: number = 0;
23 private _size: number = 0;
24 private _totalAdded: number = 0;
25 readonly capacity: number;
26
27 constructor(capacity: number) {
28 this.capacity = capacity;
29 this.buffer = new Array(capacity);
30 }
31
32 push(entry: T): void {
33 const index = (this.head + this._size) % this.capacity;
34 this.buffer[index] = entry;
35 if (this._size < this.capacity) {
36 this._size++;
37 } else {
38 // Buffer full — advance head (overwrites oldest)
39 this.head = (this.head + 1) % this.capacity;
40 }
41 this._totalAdded++;
42 }
43
44 /** Return entries in insertion order (oldest first) */
45 toArray(): T[] {
46 const result: T[] = [];
47 for (let i = 0; i < this._size; i++) {
48 result.push(this.buffer[(this.head + i) % this.capacity] as T);
49 }
50 return result;
51 }
52
53 /** Return the last N entries (most recent first → reversed to oldest first) */
54 last(n: number): T[] {
55 const count = Math.min(n, this._size);
56 const result: T[] = [];
57 const start = (this.head + this._size - count) % this.capacity;
58 for (let i = 0; i < count; i++) {
59 result.push(this.buffer[(start + i) % this.capacity] as T);
60 }
61 return result;
62 }
63
64 get length(): number {
65 return this._size;
66 }
67
68 get totalAdded(): number {
69 return this._totalAdded;
70 }
71
72 clear(): void {
73 this.head = 0;
74 this._size = 0;
75 // Don't reset totalAdded — flush cursor depends on it
76 }
77

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected