All files / use-memory-monitor/src/utils circularBuffer.ts

83.75% Statements 67/80
70% Branches 14/20
94.11% Functions 16/17
82.43% Lines 61/74

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                  41x 41x 41x                   41x 2x     39x 39x                   131x 131x   131x 107x     24x                   34x   34x 98x 98x     34x                   6x 6x   6x 6x 11x 11x     6x                 4x 1x     3x 3x                 3x 1x     2x                   9x 3x     6x 6x             9x             2x             4x             3x             3x 3x 3x 3x                                                                                         2x 6x 6x                   1x 3x 3x                     2x   2x 6x 6x     2x                   2x   2x 8x 8x   8x 2x       2x      
/**
 * A fixed-size circular buffer (ring buffer) for efficient history storage.
 * Provides O(1) push operations and automatically overwrites oldest entries
 * when capacity is reached.
 *
 * @template T - Type of items stored in the buffer
 */
export class CircularBuffer<T> {
  private buffer: (T | undefined)[];
  private head: number = 0;
  private tail: number = 0;
  private _size: number = 0;
  private _capacity: number;
 
  /**
   * Create a new circular buffer with the specified capacity
   *
   * @param capacity - Maximum number of items the buffer can hold
   * @throws Error if capacity is less than 1
   */
  constructor(capacity: number) {
    if (capacity < 1) {
      throw new Error("CircularBuffer capacity must be at least 1");
    }
 
    this._capacity = capacity;
    this.buffer = new Array(capacity);
  }
 
  /**
   * Add an item to the buffer.
   * If the buffer is full, the oldest item will be overwritten.
   *
   * @param item - Item to add
   */
  push(item: T): void {
    this.buffer[this.tail] = item;
    this.tail = (this.tail + 1) % this._capacity;
 
    if (this._size < this._capacity) {
      this._size++;
    } else {
      // Buffer is full, move head forward (overwrite oldest)
      this.head = (this.head + 1) % this._capacity;
    }
  }
 
  /**
   * Get all items in the buffer as an array, from oldest to newest.
   *
   * @returns Array of items in insertion order (oldest first)
   */
  toArray(): T[] {
    const result: T[] = [];
 
    for (let i = 0; i < this._size; i++) {
      const index = (this.head + i) % this._capacity;
      result.push(this.buffer[index] as T);
    }
 
    return result;
  }
 
  /**
   * Get the most recent N items from the buffer.
   *
   * @param count - Number of items to retrieve
   * @returns Array of most recent items (oldest first within the slice)
   */
  getRecent(count: number): T[] {
    const actualCount = Math.min(count, this._size);
    const result: T[] = [];
 
    const startOffset = this._size - actualCount;
    for (let i = 0; i < actualCount; i++) {
      const index = (this.head + startOffset + i) % this._capacity;
      result.push(this.buffer[index] as T);
    }
 
    return result;
  }
 
  /**
   * Get the most recently added item.
   *
   * @returns The most recent item, or undefined if buffer is empty
   */
  get last(): T | undefined {
    if (this._size === 0) {
      return undefined;
    }
 
    const lastIndex = (this.tail - 1 + this._capacity) % this._capacity;
    return this.buffer[lastIndex];
  }
 
  /**
   * Get the oldest item in the buffer.
   *
   * @returns The oldest item, or undefined if buffer is empty
   */
  get first(): T | undefined {
    if (this._size === 0) {
      return undefined;
    }
 
    return this.buffer[this.head];
  }
 
  /**
   * Get an item at a specific index (0 = oldest).
   *
   * @param index - Index of the item to retrieve
   * @returns The item at the index, or undefined if out of bounds
   */
  at(index: number): T | undefined {
    if (index < 0 || index >= this._size) {
      return undefined;
    }
 
    const bufferIndex = (this.head + index) % this._capacity;
    return this.buffer[bufferIndex];
  }
 
  /**
   * Current number of items in the buffer.
   */
  get size(): number {
    return this._size;
  }
 
  /**
   * Maximum capacity of the buffer.
   */
  get capacity(): number {
    return this._capacity;
  }
 
  /**
   * Check if the buffer is empty.
   */
  get isEmpty(): boolean {
    return this._size === 0;
  }
 
  /**
   * Check if the buffer is full.
   */
  get isFull(): boolean {
    return this._size === this._capacity;
  }
 
  /**
   * Clear all items from the buffer.
   */
  clear(): void {
    this.buffer = new Array(this._capacity);
    this.head = 0;
    this.tail = 0;
    this._size = 0;
  }
 
  /**
   * Resize the buffer to a new capacity.
   * If the new capacity is smaller, the oldest items will be discarded.
   * If the new capacity is larger, all existing items are preserved.
   *
   * @param newCapacity - New maximum capacity
   * @throws Error if newCapacity is less than 1
   */
  resize(newCapacity: number): void {
    if (newCapacity < 1) {
      throw new Error("CircularBuffer capacity must be at least 1");
    }
 
    if (newCapacity === this._capacity) {
      return;
    }
 
    // Get current items in order
    const items = this.toArray();
 
    // If new capacity is smaller, keep only the most recent items
    const itemsToKeep = newCapacity < items.length
      ? items.slice(items.length - newCapacity)
      : items;
 
    // Reset buffer with new capacity
    this._capacity = newCapacity;
    this.buffer = new Array(newCapacity);
    this.head = 0;
    this.tail = 0;
    this._size = 0;
 
    // Re-add items
    for (const item of itemsToKeep) {
      this.push(item);
    }
  }
 
  /**
   * Iterate over all items in the buffer (oldest to newest).
   */
  *[Symbol.iterator](): Iterator<T> {
    for (let i = 0; i < this._size; i++) {
      const index = (this.head + i) % this._capacity;
      yield this.buffer[index] as T;
    }
  }
 
  /**
   * Apply a function to each item in the buffer.
   *
   * @param callback - Function to call for each item
   */
  forEach(callback: (item: T, index: number) => void): void {
    for (let i = 0; i < this._size; i++) {
      const bufferIndex = (this.head + i) % this._capacity;
      callback(this.buffer[bufferIndex] as T, i);
    }
  }
 
  /**
   * Map items to a new array.
   *
   * @param callback - Function to transform each item
   * @returns Array of transformed items
   */
  map<U>(callback: (item: T, index: number) => U): U[] {
    const result: U[] = [];
 
    for (let i = 0; i < this._size; i++) {
      const bufferIndex = (this.head + i) % this._capacity;
      result.push(callback(this.buffer[bufferIndex] as T, i));
    }
 
    return result;
  }
 
  /**
   * Filter items based on a predicate.
   *
   * @param predicate - Function to test each item
   * @returns Array of items that pass the test
   */
  filter(predicate: (item: T, index: number) => boolean): T[] {
    const result: T[] = [];
 
    for (let i = 0; i < this._size; i++) {
      const bufferIndex = (this.head + i) % this._capacity;
      const item = this.buffer[bufferIndex] as T;
 
      if (predicate(item, i)) {
        result.push(item);
      }
    }
 
    return result;
  }
}