I have been familiarising myself with Koa (http://koajs.com/). Many of the examples include star character in place of function name. For instance in the hello world example there is:
var koa = require('koa');
var app = koa();
app.use(function *(){
this.body = 'Hello World';
});
app.listen(3000);
What does this star mean?
The function* declaration ( function keyword followed by an asterisk) defines a generator function, which returns a Generator object.
The JavaScript in operator is used to check if a specified property exists in an object or in its inherited properties (in other words, its prototype chain). The in operator returns true if the specified property exists. Anatomy of a simple JavaScript object.
It generally creates an "iterator" so you can yield result's one at a time.
Similar to C#'s yield key work.
Example
The “infinite” sequence of Fibonacci numbers (notwithstanding behavior around 2^53):
function* fibonacci() {
let [prev, curr] = [0, 1];
for (;;) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
Generators can be iterated over in loops:
for (n of fibonacci()) {
// truncate the sequence at 1000
if (n > 1000)
break;
print(n);
}
Generators are iterators:
let seq = fibonacci();
print(seq.next()); // 1
print(seq.next()); // 2
print(seq.next()); // 3
print(seq.next()); // 5
print(seq.next()); // 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With