iteragain
Version:
Javascript Iterable/Iterator/Generator-function utilities.
46 lines • 1.65 kB
JavaScript
import ConcatIterator from './ConcatIterator';
import RepeatIterator from './RepeatIterator';
/**
* Iterates through all keys in an object. Optionally provides traversal order. Does not support circular references and
* will throw a RangeError with max call stack exceeded.
* @todo // TODO: Add support for BFS traversal order.
*/
export class ObjectIterator {
constructor(object, traversal = 'post-order-DFS') {
this.traversal = traversal;
this.inner = null;
this.arr = [];
this.push(object);
}
[Symbol.iterator]() {
return this;
}
next(...args) {
if (this.inner) {
const next = this.inner.next(...args);
if (!next.done)
return next;
this.inner = null;
return this.next(...args);
}
if (!this.arr.length)
return { done: true, value: undefined };
const next = this.arr.shift(); // Previous line ensures this is not undefined.
if (this.isObject(next[1])) {
this.inner = new ConcatIterator(this.traversal === 'post-order-DFS'
? [new ObjectIterator(next[1]), new RepeatIterator(next, 1)]
: [new RepeatIterator(next, 1), new ObjectIterator(next[1])]);
return this.next(...args);
}
return { value: next, done: false };
}
isObject(value) {
return typeof value === 'object' && value !== null;
}
push(obj) {
for (const key of Object.keys(obj))
this.arr.push([key, obj[key], obj]);
}
}
export default ObjectIterator;
//# sourceMappingURL=ObjectIterator.js.map