Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the star mean in function definition like "function* ()"? [duplicate]

 function*() { .... }

I just found that form of definition in some other js code, what does the star mean indeed? Thanks

like image 456
fifth Avatar asked Apr 25 '14 05:04

fifth


2 Answers

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;
}
like image 105
T.J. Crowder Avatar answered Oct 21 '22 13:10

T.J. Crowder


From here

A function with a * token is known as a generator function. The following two unary operators are only allowed in the immediate body of a generator function (i.e., in the body but not nested inside another function):

AssignmentExpression:
    ...
    YieldExpression

YieldExpression:
    "yield" ("*"? AssignmentExpression)?

An early error is raised if a yield or yield* expression occurs in a non-generator function.

Also check the MDN and What Is This Thing Called Generators?

like image 24
Rahul Tripathi Avatar answered Oct 21 '22 13:10

Rahul Tripathi