To get the first nvalues iterator, you can use one of:
Array.from({length: n}, function(){ return this.next().value; }, iterator);
Array.from({length: n}, (i => () => i.next().value)(iterator));
To get iteratorarbitrary iterable, use:
const iterator = iterable[Symbol.iterator]();
In your case, given the function of the generator Z:
Array.from({length: 3}, function(){ return this.next().value; }, Z());
If you need this function more often, you can create a generator function:
function* take(iterable, length) {
const iterator = iterable[Symbol.iterator]();
while (length-- > 0) yield iterator.next().value;
}
const set = new Set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
console.log(...take(set, 3));
Run code source
share