Subscribed unsubscribe Subscribe Subscribe

枕を欹てて聴く

香炉峰の雪は簾を撥げて看る

YieldExpression with delegate

ECMAScript

In the latest ECMA262 6th draft (rev15), YieldExpression with delegate detailed algorithm is defined.

Reading the spec algortithm, I think this is very useful to put together iterators to make a complex iterator.

edit: I've reported issues in the spec about this section. https://bugs.ecmascript.org/show_bug.cgi?id=1486 https://bugs.ecmascript.org/show_bug.cgi?id=1487

For example,

function* gen() {
    for (let i = 0; i < 100; ++i) {
        yield i;
    }
}

function* main() {
     yield * gen();
}

for (let i of main()) {
    console.log(i);  // 0 -> 99
}
function* gen() {
    for (var i = 0; i < 100; ++i) {
        var receive = yield i;
        console.log(receive);    // 0, 1, 4, 9, ... , 9801
    }
}

function* main() {
    yield* gen();
}

let result = { done: false, value: undefined };
let iterator = main();
do {
    result = iterator.next(result.value * result.value);
    if (result.done) {
        break;
    }
    console.log(result.value);  // 0, 1, 2, 3, ..., 99
} while (true);
// the result of console is interleaved,
// 0, 0, 1, 1, 2, 4, 3, 9, ...

So we can easily create a new iterator for our data types.

function MapWithArray() {
    this.map = new Map();
    this.array = [];
}

function* MapWithArrayIterator(obj) {
    yield * obj.map;
    yield * obj.array;
}

let data = new MapWithArray;
let iterator = MapWithArrayIterator(data);