簡介產生器函式

``````function* range(start, end) {
for(let i = start; i < end; i++) {
yield i;
}
}

let r = range(3, 8);
for(let n of r) {
console.log(n);
}
``````

``````> function* range(start, end) {
...     for(let i = start; i < end; i++) {
.....           yield i;
.....   }
... }
undefined
> let g = range(2, 5);
undefined
> g.next();
{ value: 2, done: false }
> g.next();
{ value: 3, done: false }
> g.next();
{ value: 4, done: false }
> g.next();
{ value: undefined, done: true }
>
``````

``````function* producer(n) {
for(let data = 0; data < n; data++) {
console.log('生產了：', data);
yield data;
}
}

function* consumer(n) {
for(let i = 0; i < n; i++) {
let data = yield;
console.log('消費了：', data);
}
}

function clerk(n, producer, consumer) {
console.log(`執行 \${n} 次生產與消費`);
let p = producer(n);
let c = consumer(n);
c.next();
for(let data of p) {
c.next(data);
}
}

clerk(5, producer, consumer);
``````

``````執行 5 次生產與消費

``````

``````function* range(start, end) {
for(let i = start; i < end; i++) {
yield i;
}
}

function* np_range(n) {
for(let i of range(0 - n, 0)) {
yield i
}

for(let i of range(1, n + 1)) {
yield i
}
}

for(let i of np_range(3)) {
console.log(i);
}
``````

``````function* range(start, end) {
for(let i = start; i < end; i++) {
yield i;
}
}

function* np_range(n) {
yield* range(0 - n, 0);
yield* range(1, n + 1);
}

for(let i of np_range(3)) {
console.log(i);
}
``````