function* infiniteIterables() {
for (let i = 1; ; i++) {
yield Array(i).fill(i);
}
}
// BAD:
// Iterator.concat(...infiniteIterables());
// The spread operator never finishes
// GOOD:
const it = infiniteIterables().flatMap((x) => x);
// Infinite sequence of numbers: 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, ...Iterator.concat() / notebook
Iterator.concat()
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
function* concat(...iterables) {
for (const iterable of iterables) {
yield* iterable;
}
}const map1 = new Map([
["a", 1],
["b", 2],
]);
const map2 = new Map([
["c", 3],
["d", 4],
]);
const map3 = new Map([
["a", 5],
["e", 6],
]);
const map = new Map(Iterator.concat(map1, map2, map3));
console.log(map);
// Map(5) {'a' => 5, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 6}function* it1() {
yield 1;
yield 2;
}
function* it2() {
let i = 3;
while (true) {
yield i++;
}
}
function* it3() {
yield "done";
}
const it = Iterator.concat(it1(), it2(), it3());
for (const value of it.take(10)) {
console.log(value); // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
}
// "done" is never reachedconst array = [1, 2, 3];
const set = new Set([4, 5, 6]);
function* gen() {
yield 7;
yield 8;
yield 9;
}
const it = Iterator.concat(array, set, gen());
console.log([...it]); // [1, 2, 3, 4, 5, 6, 7, 8, 9]const array = [1, "two", 3];
const set = new Set([true, {}]);
const it = Iterator.concat(array, set);
console.log([...it]); // [1, "two", 3, true, {}]const nonIterable = {
next() {
return { done: true };
},
};
const it = Iterator.concat(nonIterable); // TypeError: object is not iterableconst arrayIterator = [1, 2, 3][Symbol.iterator]();
const it = Iterator.concat(arrayIterator); // No errorconst nonIterable = {
next() {
return { done: true };
},
};
const it = Iterator.concat(Iterator.from(nonIterable)); // No errorconst nonIterable = {
next() {
return { done: true };
},
};
const it = [nonIterable].values().flatMap((x) => x); // No error