Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Circular Buffer Implementation in TypeScript

11 min readbeginner
Website QA and SEO audits

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

A ring buffer stores a fixed number of elements in one contiguous block and moves two integer indices instead of moving data: writes advance one cursor, reads advance the other, and both wrap at the end of the block. Nothing is ever shifted and no node is ever allocated, which is why it beats a linked structure at the same big-O. The one real design constraint is that head == tail is ambiguous: it means both empty and full. The three honest fixes are a separate count field, deliberately wasting one slot, or letting the cursors run free and masking with capacity minus one when capacity is a power of two. On top sit two policy choices: overwrite the oldest or reject the write when full, and whether one producer and one consumer may run without a lock, which needs only that the writer publishes its cursor after the payload and the reader loads that cursor before the payload. The eight languages diverge because each answers different questions: does an array hold values or references, does an integer wrap or trap or grow without bound, what does the memory model demand to publish a cursor, and must a vacated slot be cleared so the collector can reclaim what it held.

Circular Buffer in TypeScript: what you actually reach for

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.

TypeScript implementation

Reviewers want the generic parameter threaded through, never any and never unknown casts scattered at call sites. They want #head rather than private head, because only the first survives compilation. They want the emptiness test to read a numeric count field rather than compare a slot against a sentinel, and they want the one unavoidable cast, the read of a slot known to be occupied, isolated to a single line with a comment explaining the invariant that justifies it.
typescript
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 Free

The TypeScript-specific 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. 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.

Performance in TypeScript, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Circular Buffer between languages.

Real-World Applications

Circular Buffer applies wherever its problem shape appears in your own code. In TypeScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Circular Buffer helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Circular Buffer appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Circular Buffer over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Circular Buffer to build pattern recognition. In TypeScript, demonstrate proficiency with generics and type guards to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic TypeScript code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Most AI and dev tools have a student plan. See which ones and how to claim them on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.