UNPKG

@contextjs/collections

Version:

Strongly-typed collection classes for TypeScript, including List, Dictionary, Queue, Stack, and HashSet.

46 lines (45 loc) 1.23 kB
export class List { items; size; constructor(initialCapacity = 4) { this.items = new Array(initialCapacity); this.size = 0; } add(item) { this.ensureCapacity(); this.items[this.size++] = item; } remove(index) { if (index < 0 || index >= this.size) return; for (let i = index; i < this.size - 1; i++) this.items[i] = this.items[i + 1]; this.items[this.size - 1] = undefined; this.size--; } get(index) { if (index < 0 || index >= this.size) return null; return this.items[index]; } clear() { for (let i = 0; i < this.size; i++) this.items[i] = undefined; this.size = 0; } get count() { return this.size; } toArray() { return this.items.slice(0, this.size); } ensureCapacity() { if (this.size >= this.items.length) { const newCapacity = this.items.length === 0 ? 4 : this.items.length * 2; const newArray = new Array(newCapacity); for (let i = 0; i < this.size; i++) newArray[i] = this.items[i]; this.items = newArray; } } }