I'm trying to write a function that can take either a list or a generator as input. For example, this function:
function x(l) {
for (let i of l) {
console.log(i);
}
for (let i of l) {
console.log(i);
}
}
If I run it like this:
x([1,2,3])
It will display:
1
2
3
1
2
3
Now I want to use a generator as input:
function *y() {
yield 5
yield 6
yield 7
}
These don't work:
x(y())
x(y)
The output is:
5
6
7
undefined
What do I need to do so that I can make it work?
In terms of Java, the function y
above is a Generator and y()
is an Iterator. [1,2,3]
is a list and in Java, lists are generators. But the javascript for loop expects an iterator, which means that it can't be restarted. This seems like a flaw in javascript that the for loop works on iterators and not generators.