JavaScript/Common Iteration Interfaces
Common Iteration Interfaces
は、JavaScript における反復操作を定義する標準的なインターフェースのコレクションです。これらのインターフェースは、様々なデータ構造を一貫した方法で反復処理するための共通の仕組みを提供します[1]。
概要
JavaScriptにおける反復のためのインターフェースは、以下の標準インターフェースで構成されています:
Iterable Interface
: 反復可能なオブジェクトを定義Iterator Interface
: 順次アクセスを提供するオブジェクトを定義Iterator Interface
: 非同期反復可能なオブジェクトを定義Iterator Interface
: 非同期順次アクセスを提供するオブジェクトを定義Iterator Interface
: 反復結果を表現するオブジェクトを定義
例
複数の反復インターフェースを使用するプログラム
以下のプログラムは、様々な反復インターフェースを使用して、同期および非同期の反復処理を実装します。
// イテラブルオブジェクト (Iterable Interface) const iterableObj = { data: [1, 2, 3], [Symbol.iterator]() { let index = 0; return { // イテレータオブジェクト (Iterator Interface) next() { // イテレータ結果 (IteratorResult Interface) if (index < this.data.length) { return { value: this.data[index++], done: false }; } return { value: undefined, done: true }; } }; } }; // 非同期イテラブルオブジェクト (Async Iterable Interface) const asyncIterableObj = { data: [4, 5, 6], [Symbol.asyncIterator]() { let index = 0; return { // 非同期イテレータオブジェクト (Async Iterator Interface) async next() { await new Promise(resolve => setTimeout(resolve, 100)); // イテレータ結果 (IteratorResult Interface) if (index < this.data.length) { return { value: this.data[index++], done: false }; } return { value: undefined, done: true }; } }; } }; // 同期反復 for (const item of iterableObj) { console.log(item); // 1, 2, 3 } // 非同期反復 (async () => { for await (const item of asyncIterableObj) { console.log(item); // 4, 5, 6 } })();
このプログラムでは、Iterable
、Iterator
、Async Iterable
、Async Iterator
、IteratorResult
の各インターフェースを実装し、同期および非同期の反復処理を行っています。
ジェネレータを使用した反復インターフェースの実装
以下のプログラムは、ジェネレータ関数を使用して反復インターフェースを簡潔に実装します。
// ジェネレータを使用したイテラブルオブジェクト function* createGenerator() { yield 1; yield 2; yield 3; } // 非同期ジェネレータを使用した非同期イテラブルオブジェクト async function* createAsyncGenerator() { await new Promise(resolve => setTimeout(resolve, 100)); yield 4; await new Promise(resolve => setTimeout(resolve, 100)); yield 5; await new Promise(resolve => setTimeout(resolve, 100)); yield 6; } // 同期反復 const generator = createGenerator(); for (const item of generator) { console.log(item); // 1, 2, 3 } // 非同期反復 (async () => { const asyncGenerator = createAsyncGenerator(); for await (const item of asyncGenerator) { console.log(item); // 4, 5, 6 } })();
このプログラムでは、ジェネレータ関数と非同期ジェネレータ関数を使用して、反復インターフェースを簡潔に実装しています。ジェネレータ関数はSymbol.iterator
メソッドを、非同期ジェネレータ関数はSymbol.asyncIterator
メソッドを自動的に実装します。
注意点
- 相互運用性: 反復インターフェースは、様々なデータ構造が一貫した方法で反復処理されることを可能にします。
- プロトコル: これらのインターフェースは「イテレーションプロトコル」を形成し、ECMAScriptの反復操作の基盤となります。
- 組み込みオブジェクト: 配列、文字列、Map、Set、TypedArrayなどの多くの組み込みオブジェクトは、これらのインターフェースを実装しています。
- カスタムコレクション: カスタムデータ構造を作成する際に、これらのインターフェースを実装することで、標準的な反復操作をサポートすることができます。
脚註
- ↑ これらは、ECMAScript の反復プロトコルの基盤となるものです。