JavaScriptプログラム

JavaScript ES6 genenator

'use strict';
const nextTeam = {
lead: 'Tsune',
boss: 'Yoshitsune'
};
const testingTeam = {
nextTeam,
lead: 'Yamada',
tester: 'Suzuki'
};
const engineeringTeam = {
testingTeam,
size: 3,
department: 'development',
lead: 'Oda',
manager: 'Tokugawa',
engineer: 'Toyotomi'
};

function* TeamIterator(team){
yield team.lead;
yield team.manager;
yield team.engineer;
const testingTeamGenarator = TestingTeamIterator(team.testingTeam);
yield* testingTeamGenarator;
}
function* TestingTeamIterator(team){
yield team.lead;
yield team.tester;
const nextTeamGenarator = NextTeamIterator(team.nextTeam);
yield* nextTeamGenarator;
}
function* NextTeamIterator(team){
yield team.lead;
yield team.boss;
}
const names = [];
for(let name of TeamIterator(engineeringTeam)){
names.push(name);
}
console.log(names); // [ "Oda", "Tokugawa", "Toyotomi", "Yamada", "Suzuki", "Tsune", "Yoshitsune"]

generatorとfor .. of..で配列に限らず値を抽出できるようになります。

また、generator内部でgeneratorのオブジェクトを作成することにより委譲することもできます。

上記のコードは冗長なので[Symbol.iterator]を使って簡潔にします。for ofは配列の[Symbol.iterator]を探しに行きますので、その性質を使うために実装します。

'use strict';
const nextTeam = {
lead: 'Tsune',
boss: 'Yoshitsune',
[Symbol.iterator]: function* (){
yield this.lead;
yield this.boss;
}
};
const testingTeam = {
nextTeam,
lead: 'Yamada',
tester: 'Suzuki',
[Symbol.iterator]: function* (){
yield this.lead;
yield this.tester;
yield* this.nextTeam;
}
};
const engineeringTeam = {
testingTeam,
size: 3,
department: 'development',
lead: 'Oda',
manager: 'Tokugawa',
engineer: 'Toyotomi',
[Symbol.iterator]: function* (){
yield this.lead;
yield this.manager;
yield this.engineer;
yield* this.testingTeam;
}
};
const names = [];
for(let name of engineeringTeam){
names.push(name);
}
console.log(names); // [ "Oda", "Tokugawa", "Toyotomi", "Yamada", "Suzuki", "Tsune", "Yoshitsune" ]

コメントを残す