1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
/* 自作のイテレータを自作のジェネレータ関数にかけてみる */ 'use strict'; const p = console.log; const generatorFunction = function* (a) { yield* a; }; const createIterableObject = () => { const iterableObject = { [Symbol.iterator]: () => { let cnt = 0; const iterator = { next: () => { if (cnt < 5) { return { value: cnt++, done: false }; } return { value: undefined, done: true }; }, }; return iterator; }, }; return iterableObject; }; const mainIteratorAndGenerator = () => { const myIterableObject = createIterableObject(); const myGenerator = generatorFunction(myIterableObject); p(...myGenerator); // 0 1 2 3 4 p(...myGenerator); // p(...myIterableObject); // 0 1 2 3 4 p(...myIterableObject); // 0 1 2 3 4 }; // module.exports = mainIteratorAndGenerator; mainIteratorAndGenerator(); |
1 2 3 4 |
0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 |