ジェネレーターとは
for...ofループの動作を簡単にカスタマイズできる仕組み。
サンプルコード
簡単な例
function* colors() {
yield 'red';
yield 'blud';
yield 'green';
}
const myColors = [];
for (let color of colors()) {
myColors.push(color)
}
iteratorを別に実装する例
const testingTeam = {
lead: '由紀子',
tester: '隆'
}
const engineeringTeam = {
testingTeam,
size: 3,
department: '開発部',
lead: '太郎',
manager: '花子',
engineer: '次郎'
};
function* TestingTeamIterator(team) {
yield team.lead;
yield team.tester;
}
function* TeamIterator(team) {
yield team.lead;
yield team.manager;
yield team.engineer;
const testingTeamGenerator = TestingTeamIterator(team.testingTeam);
yield* testingTeamGenerator;
}
const names = [];
for(let value of TeamIterator(engineeringTeam)) {
names.push(value);
}
iteratorを組み込んだ例
const testingTeam = {
lead: '由紀子',
tester: '隆',
[Symbol.iterator]: function* () {
yield this.lead;
yield this.tester;
}
}
const engineeringTeam = {
testingTeam,
size: 3,
department: '開発部',
lead: '太郎',
manager: '花子',
engineer: '次郎',
[Symbol.iterator]: function* () {
yield this.lead;
yield this.manager;
yield this.engineer;
yield* this.testingTeam;
}
};
const names = [];
for(let value of engineeringTeam) {
names.push(value);
}
ツリー構造を再帰で呼び出す例
class Comment {
constructor(content, children) {
this.content = content;
this.children = children;
}
*[Symbol.iterator]() {
yield this.content;
for (let child of this.children) {
yield* child;
}
}
}
const children = [
new Comment("賛成", []),
new Comment("反対", []),
new Comment("うーん", [])
]
const tree = new Comment("いい記事ですね!", children);
const nodes = [];
for (let node of tree) {
nodes.push(node);
}