TheAlgorithms/JavaScript · error · RangeError

Capacity should be greater than 0

Error message

Capacity should be greater than 0

What it means

Thrown by the LRUCache capacity setter when the new value is negative. Note the guard is `newCapacity < 0` but the message reads 'greater than 0', so the message is slightly misleading: 0 is actually accepted (it just empties the cache via eviction until capacity is reached), only negatives throw.

Source

Thrown at Cache/LRUCache.js:41

    return Object.freeze({
      misses: this.misses,
      hits: this.hits,
      capacity: this.capacity,
      size: this.size
    })
  }

  get size() {
    return this.cache.size
  }

  get capacity() {
    return this.#capacity
  }

  set capacity(newCapacity) {
    if (newCapacity < 0) {
      throw new RangeError('Capacity should be greater than 0')
    }

    if (newCapacity < this.capacity) {
      let diff = this.capacity - newCapacity

      while (diff--) {
        this.#removeLeastRecentlyUsed()
      }
    }

    this.#capacity = newCapacity
  }

  /**
   * delete oldest key existing in map by the help of iterator
   */
  #removeLeastRecentlyUsed() {
    this.cache.delete(this.cache.keys().next().value)

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Assign a non-negative value: cache.capacity = Math.max(0, newSize).
  2. Clamp computed sizes before assignment.
  3. Be aware 0 is permitted and will evict everything; the guard only blocks negatives.

Example fix

// before
cache.capacity = currentLoad - reserved // can be negative
// after
cache.capacity = Math.max(0, currentLoad - reserved)
Defensive patterns

Strategy: validation

Validate before calling

function resizeLRU(cache, newSize) {
  cache.capacity = Math.max(0, newSize);
}

Try / catch

try { cache.capacity = newSize; }
catch (e) {
  if (e instanceof RangeError && /greater than 0/.test(e.message)) {
    cache.capacity = Math.max(0, newSize);
  } else throw e;
}

Prevention

When it happens

Trigger: cache.capacity = -5, or assigning a computed size that goes negative (e.g. after subtracting a budget).

Common situations: Dynamically resizing the cache from a metric that dipped below zero, or a subtraction underflow when shrinking.

Related errors


AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13). Data as JSON: /api/errors/5924df8e47da4591. Report an issue: GitHub.