I came across this idom: function* (){ ... }
from this page https://github.com/jmar777/suspend and not sure what does it do.
Could anyone explain? Thanks!
I came across this idom: function* (){ ... }
from this page https://github.com/jmar777/suspend and not sure what does it do.
Could anyone explain? Thanks!
It means that the function is a generator function. Quoting from http://wiki.ecmascript.org/doku.php?id=harmony:generators#syntax
A function with a * token is known as a generator function.
Normal functions execute and return the result. But generators yield values and wait for them to get invoked again. Then the function will resume its execution.
Generator functions are normally iterated over. Since, they yield the values and wait from the next function call to resume execution, they are useful for infinite values generators.
They are memory efficient as well. For example, lets say you want to generate 10000000 numbers, if we store them in an Array, we might exhaust the machine's memory. But if we use a generator, we can generate one number, yield value and when called again execution will be resumed and the next number can be generated.
We can look at the examples, here,
function* fibonacci() {
let [prev, curr] = [0, 1];
for (;;) { // Infinite looping
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
And as I said, generators are iterated like this
for (n of fibonacci()) {
// truncate the sequence at 1000
if (n > 1000)
break;
print(n);
}
See the generator function actually has an infinite loop. When yield curr
is executed, value will be returned to n
in n of fibonacci()
. That is used in the iteration and when the generator is called again, it resumes the execution (it retains the data in variables as well) and generates the next element.