UNPKG

iteragain

Version:

Javascript Iterable/Iterator/Generator-function utilities.

41 lines 1.37 kB
import isIterable from '../isIterable'; import isIterator from '../isIterator'; import toIterator from '../toIterator'; /** Flattens an iterator `depth` number of levels. Nested string values are left intact (not split into characters). */ export class FlattenIterator { constructor(iterator, depth) { this.iterator = iterator; this.depth = depth; this.inner = null; } [Symbol.iterator]() { return this; } next(...args) { if (this.depth < 1) return this.iterator.next(...args); let next; if (this.inner) { next = this.inner.next(...args); if (next.done) { this.inner = null; return this.next(...args); } return next; } next = this.iterator.next(...args); if (typeof next.value !== 'string') { if (isIterator(next.value)) { this.inner = new FlattenIterator(next.value, this.depth - 1); return this.next(...args); } else if (isIterable(next.value)) { this.inner = new FlattenIterator(toIterator(next.value), this.depth - 1); return this.next(...args); } } return next; } } export default FlattenIterator; //# sourceMappingURL=FlattenIterator.js.map