TheAlgorithms/JavaScript · error · TypeError

Invalid capacity

Error message

Invalid capacity

What it means

LRUCache constructor requires a non-negative integer capacity. It uses Number.isInteger and a >=0 check, then coerces with ~~capacity. Negative, fractional, NaN, or non-numeric capacities are rejected because the internal Map-based eviction logic needs a whole-number size bound.

Source

Thrown at Cache/LRUCache.js:11

class LRUCache {
  // LRU Cache to store a given capacity of data
  #capacity

  /**
   * @param {number} capacity - the capacity of LRUCache
   * @returns {LRUCache} - sealed
   */
  constructor(capacity) {
    if (!Number.isInteger(capacity) || capacity < 0) {
      throw new TypeError('Invalid capacity')
    }

    this.#capacity = ~~capacity
    this.misses = 0
    this.hits = 0
    this.cache = new Map()

    return Object.seal(this)
  }

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

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Pass a non-negative integer literal: new LRUCache(128).
  2. Parse and validate config-derived values: Math.max(0, Math.trunc(Number(raw))).
  3. Default the argument explicitly when it may be undefined.

Example fix

// before
new LRUCache(process.env.CACHE_SIZE) // string
// after
new LRUCache(Math.max(0, Math.trunc(Number(process.env.CACHE_SIZE) || 0)))
Defensive patterns

Strategy: validation

Validate before calling

function makeLRU(raw) {
  const cap = Math.max(0, Math.trunc(Number(raw) || 0));
  return new LRUCache(cap);
}

Type guard

/** @param {unknown} c @returns {c is number} */
const isNonNegInt = c => Number.isInteger(c) && c >= 0;

Try / catch

try { return new LRUCache(rawCap); }
catch (e) {
  if (e instanceof TypeError && e.message === 'Invalid capacity') {
    return new LRUCache(Math.max(0, Math.trunc(Number(rawCap) || 0)));
  }
  throw e;
}

Prevention

When it happens

Trigger: new LRUCache(-1), new LRUCache(2.5), new LRUCache(NaN), new LRUCache("8"), new LRUCache(undefined) (NaN), or new LRUCache() (undefined).

Common situations: Reading capacity from an env var or config string without converting, computing capacity from a division that yields a fraction, or forgetting the argument entirely.

Related errors


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