The generator function is difficult to explain, but in a nutshell, it is a "function that returns a value in small quantities (a function that creates)". In Python, for example, you can use it like this. It may be called a function that creates an italator.
def firstn(n):
num = 0
while num < n:
yield num
num += 1
gen = firstn(10)
print gen.next() # —> 0
print gen.next() # —> 1
print gen.next() # —> 2
…
print gen.next() # —>11th time StopIteration exception occurs
Of course, it can also be used in for loops and list comprehensions.
for n in firstn(10):
print n,
# —> 0 1 2 3 4 5 6 7 8 9
print [n for n in firstn(10)]
# -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
So, it seems that this generator function can also be used in JavaScript. It will be officially standardized in ES6 (ECMAScript version 6), but some implementations have already begun to incorporate this feature.
Node.js is also officially adopted in the next stable version v0.12, so the generator can be used in v0.11. So I tried using it.
First, rewrite the above example in JavaScript.
firstn = function* (n) {
var num = 0
while (num < n) {
yield num
num += 1
}
};
gen = firstn(10);
console.log(gen.next()); // —> { value: 0, done: false }
console.log(gen.next()); // —> { value: 1, done: false }
console.log(gen.next()); // —> { value: 2, done: false }
…
console.log(gen.next()); // —>11th time{ value: undefined, done: true }Returns
The difference from Python is that it does not return a value, but an object that has two attributes, value and done. When the iteration is over, done is true instead of raising an exception.
At runtime, use node —harmony
. "Harmony" seems to be the code name of ES6.
And this can also be used in a for loop
for (n of firstn(10)) {
process.stdout.write(n + " ");
}
// —> 0 1 2 3 4 5 6 7 8 9
It seems that list comprehension will be available in ES6, but it is not supported in the current latest version (0.11.9). Sorry.
Recommended Posts