Circular Buffer Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Circular Buffer runs in O(1) time and O(n) space, in TypeScript as in every other language.
- ✓TypeScript adds no runtime container, so the storage is still Array<T>, Float64Array, or Int32Array over a SharedArrayBuffer with Atomics.
- ✓Reviewers want the generic parameter threaded through, never any and never unknown casts scattered at call sites.
- ✓The TypeScript trap: Types erase, so nothing about the buffer is checked at runtime. The specific trap is using undefined or null as the empty marker: it type-checks perfectly and then breaks the moment T includes undefined, because RingBuffer<string | undefined> cannot distinguish a stored undefined from a vacant slot.
- ✓The emit is the JavaScript, so the numbers are the JavaScript numbers, with one exception that matters here: #private fields downlevel to WeakMap lookups when the compilation target is below ES2022, turning every this.#head in the hot loop into a hash lookup.
What Circular Buffer actually is
Circular Buffer in TypeScript: what you actually reach for
TypeScript implementation
export type PushResult<T> =
| { readonly kind: "stored" }
| { readonly kind: "evicted"; readonly oldest: T };
export class RingBuffer<T> {
readonly #buf: Array<T | undefined>;
readonly #mask: number;
#head = 0; // index of the oldest element
#count = 0; // count, not a sentinel: T itself may legally be undefined
constructor(capacity: number) {
if (capacity < 1 || (capacity & (capacity - 1)) !== 0) {
throw new RangeError("capacity must be a power of two");
}
this.#buf = new Array<T | undefined>(capacity).fill(undefined);
this.#mask = capacity - 1;
}
get size(): number { return this.#count; }
push(value: T): PushResult<T> {
const tail = (this.#head + this.#count) & this.#mask;
let result: PushResult<T> = { kind: "stored" };
if (this.#count === this.#buf.length) {
// Invariant: tail === head when full, so this slot is occupied.
result = { kind: "evicted", oldest: this.#buf[this.#head] as T };
this.#head = (this.#head + 1) & this.#mask;
} else {
this.#count++;
}
this.#buf[tail] = value;
return result;
}
pop(): T | undefined {
if (this.#count === 0) return undefined;
// Invariant: #count > 0, so the slot at #head is occupied.
const v = this.#buf[this.#head] as T;
this.#buf[this.#head] = undefined;
this.#head = (this.#head + 1) & this.#mask;
this.#count--;
return v;
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Circular Buffer?
TypeScript adds no runtime container, so the storage is still Array<T>, Float64Array, or Int32Array over a SharedArrayBuffer with Atomics. What it adds is the declaration. Write class RingBuffer<T> with #private fields and an internal Array<T | undefined>, and keep undefined out of the public signatures. Turn on noUncheckedIndexedAccess in tsconfig so buf[i] types as T | undefined and the uninitialized-slot problem becomes explicit instead of assumed away. Model the push result as a discriminated union, { kind: 'stored' } | { kind: 'evicted'; oldest: T }, instead of returning T | null, which collapses the two cases whenever T itself is nullable.
What is the most common TypeScript mistake when implementing Circular Buffer?
Types erase, so nothing about the buffer is checked at runtime. The specific trap is using undefined or null as the empty marker: it type-checks perfectly and then breaks the moment T includes undefined, because RingBuffer<string | undefined> cannot distinguish a stored undefined from a vacant slot. A count field fixes it; a type never can. The same erasure means private and readonly vanish from the emitted JavaScript, so any plain JS caller can reach in and move your cursors, and a capacity that arrived from JSON.parse is number by declaration and anything at all in fact. The power-of-two check you write yourself is the only guard that actually runs.
How does Circular Buffer actually perform in TypeScript?
The emit is the JavaScript, so the numbers are the JavaScript numbers, with one exception that matters here: #private fields downlevel to WeakMap lookups when the compilation target is below ES2022, turning every this.#head in the hot loop into a hash lookup. Set target to ES2022 or later and they become native private fields. Branded index types, readonly and generics cost exactly zero because they are erased. Prefer plain numeric constants over enums for the mask, since enum emit adds a runtime object lookup. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialMost AI and dev tools have a student plan. See which ones and how to claim them on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.