krahets/hello-algo · error · Error

インデックスが範囲外です

Error message

インデックスが範囲外です

What it means

Thrown by the custom dynamic-array list's get method when index is outside [0, _size). The guard runs before reading arr[index], ensuring the returned value is a real stored element. Note the bound is _size (logical length), not _capacity (allocated length).

Source

Thrown at ja/codes/typescript/chapter_array_and_linkedlist/my_list.ts:32

    /* コンストラクタ */
    constructor() {
        this.arr = new Array(this._capacity);
    }

    /* リストの長さを取得(現在の要素数) */
    public size(): number {
        return this._size;
    }

    /* リスト容量を取得する */
    public capacity(): number {
        return this._capacity;
    }

    /* 要素にアクセス */
    public get(index: number): number {
        // インデックスが範囲外なら例外を送出する。以下同様
        if (index < 0 || index >= this._size) throw new Error('インデックスが範囲外です');
        return this.arr[index];
    }

    /* 要素を更新 */
    public set(index: number, num: number): void {
        if (index < 0 || index >= this._size) throw new Error('インデックスが範囲外です');
        this.arr[index] = num;
    }

    /* 末尾に要素を追加 */
    public add(num: number): void {
        // 長さが容量に等しい場合は拡張が必要
        if (this._size === this._capacity) this.extendCapacity();
        // 新しい要素をリストの末尾に追加する
        this.arr[this._size] = num;
        this._size++;
    }

View on GitHub (pinned to 69932aed18)

Solutions

  1. Validate 0 <= index < list.size() before get().
  2. Always use size() for loop bounds, never the raw backing array length.
  3. Recompute indices after insert/remove shifts them.
  4. Treat indexOf === -1 as not-found before using it as an index.

Example fix

// before
const v = list.get(i);  // throws if i out of [0, size)

// after
if (i >= 0 && i < list.size()) {
  const v = list.get(i);
}
Defensive patterns

Strategy: validation

Validate before calling

function safeGet(list: { size(): number; get(i: number): number }, index: number) {
  if (index < 0 || index >= list.size()) return null;
  return list.get(index);
}

Type guard

const isValidReadIndex = (list: { size(): number }, i: number): boolean =>
  Number.isInteger(i) && i >= 0 && i < list.size();

Try / catch

try {
  return list.get(index);
} catch (e) {
  if (e instanceof Error && e.message === 'インデックスが範囲外です') return null;
  throw e;
}

Prevention

When it happens

Trigger: Calling get(index) with index < 0 or index >= _size; reading an index that holds stale data beyond the logical length; off-by-one in a loop bound (using capacity or array length instead of size).

Common situations: Iterating with this.arr.length instead of this.size(); using an externally cached index after removals; negative indices from indexOf returning -1.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/60dc114bd2d7d04f. Report an issue: GitHub.