๐ธnext()
method of an iterator that returns an "iteration result"
Last updated
method of an iterator that returns an "iteration result"
Last updated
JSโฉ iteration โฉ iterator โฉ next()
a method that returns an iteration result.
the argument to the next() method๏ผ
is the value of the previous yield. ( ๐ see๏ผ ๐็ฏไพ )
is ignored in the first call of next() method. (since there's no previous yield yet)
can be considered as a new starting point for the current next() call. (except for the first call, in which the argument is ignored)
the const statement๏ผ
const arg2 = yield 1; // generator code
has two execution contexts๏ผ
yield 1 // in the context of #1 next() call.
const arg2 // in the context of #2 next() call.
replit๏ผvalue of yield expression (2)
const { log } = console;
// generator code
function* ints() {
// argument to the `next(arg)` method
// ---------------------------------------------
// `arg`:
// โข is the "value" of PREVIOUS "yield expression".
// โข is ignored in the first call of next().
// (since there's NO previous yield expression)
// โข can be considered a "new starting point" for
// the "current" call of next() method.
// (except for the first call, in which `arg` is ignored)
// #1 next() call
// ---------------
// โญโ1โโฎ // 1. value for #1 call
const arg2 = yield 1 ; // (execution stops at Y.E.)
// โฐโ 2 โโฏ โฐโโ Y.E. โโโฏ // Y.E. : yield expression
// #2 next() call
// --------------
// 2. argument sent in by #2 call
// โญโโ 3 โโโฎ // 3. value for #2 call
const arg3 = yield [2, arg2]; // (execution stops at Y.E.)
// โฐโ 4 โโฏ โฐโโโโ Y.E. โโโโฏ //
// #3 next() call
// --------------
// โญโโ 5 โโโฎ // 4. argument sent in by #3 call
return [3, arg3]; // 5. "done" value for #3 call
// (the iteration is finished)
}
// table settings
const headers = [' ', 'value', 'done'];
const n = headers.length; // number of columns
const [colWidth, pad, ext] = [5, 1, 0];
const line = '-'.repeat(colWidth*n + pad*(n-1) + ext);
log(` value done`);
log(line);
// log iteration result
function logResult(r, i) {
let value = r.value === undefined ? 'x' : String(r.value);
value = value.padEnd(5, ' ');
const done = (r.done ? 'โ
' : 'โ').padEnd(4, ' ');
log(`#${i}: ${value} ${done}`);
}
// main
let it = ints();
const r1 = it.next('a'); // #1 next() call
logResult(r1, 1);
const r2 = it.next('b'); // #2 next() call
logResult(r2, 2);
const r3 = it.next('c'); // #3 next() call
logResult(r3, 3);
// output:
//
// value done
// -----------------
// #1: 1 โ
// #2: 2,b โ
// #3: 3,c โ
a Generator object is an iterable iterator, so it has this method too.