What does the star mean in function definition like "function* ()"?
In ES2015+, it defines a generator function.
Here's an example of a generator:
function* fibonacci() {
let [prev, curr] = [0, 1];
while (true) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
Various ways to use:
With a for-of
loop (another ES2015+ thing):
for (const n of fibonacci()) {
// truncate the sequence at 1000
if (n > 1000) {
break;
}
console.log(n);
}
Example:
function* fibonacci() {
let [prev, curr] = [0, 1];
while (true) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
for (const n of fibonacci()) {
// truncate the sequence at 1000
if (n > 1000) {
break;
}
console.log(n);
}
.as-console-wrapper {
max-height: 100% !important;
}
Using the iterator directly (for-of
uses it under the covers for you):
const seq = fibonacci();
console.log(seq.next().value); // 1
console.log(seq.next().value); // 2
console.log(seq.next().value); // 3
console.log(seq.next().value); // 5
console.log(seq.next().value); // 8
function* fibonacci() {
let [prev, curr] = [0, 1];
while (true) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
const seq = fibonacci();
console.log(seq.next().value); // 1
console.log(seq.next().value); // 2
console.log(seq.next().value); // 3
console.log(seq.next().value); // 5
console.log(seq.next().value); // 8
.as-console-wrapper {
max-height: 100% !important;
}