UNPKG

1.24 kBJavaScriptView Raw
1import { IterableX } from './iterablex';
2import { isIterable } from '../internal/isiterable';
3export class FlattenIterable extends IterableX {
4 constructor(source, depth) {
5 super();
6 this._source = source;
7 this._depth = depth;
8 }
9 *_flatten(source, depth) {
10 if (depth === 0) {
11 for (let item of source) {
12 yield item;
13 }
14 return undefined;
15 }
16 for (let item of source) {
17 if (isIterable(item)) {
18 for (let innerItem of this._flatten(item, depth - 1)) {
19 yield innerItem;
20 }
21 }
22 else {
23 yield item;
24 }
25 }
26 }
27 [Symbol.iterator]() {
28 return this._flatten(this._source, this._depth)[Symbol.iterator]();
29 }
30}
31/**
32 * Flattens the source sequence until the specified depth.
33 * @param {Iterable<T>} source Source sequence.
34 * @param {Number} depth The depth to flatten the source sequence.
35 * @returns {Iterable<T>} The flattened sequence, flattened to the specified depth.
36 */
37export function flatten(source, depth = Infinity) {
38 return new FlattenIterable(source, depth);
39}
40
41//# sourceMappingURL=flatten.mjs.map