|
| 1 | +import assert from 'assert'; |
| 2 | +import {Empty} from '../../../3-tree/implementations/0-Empty.js'; |
| 3 | +import {Single} from '../../../3-tree/implementations/1-Single.js'; |
| 4 | +import {Deep} from '../../../3-tree/implementations/2-Deep.js'; |
| 5 | + |
| 6 | +export const DOWNWARD = 0; |
| 7 | +export const UPWARD = 1; |
| 8 | + |
| 9 | +export default function DeepIterator() {} |
| 10 | + |
| 11 | +DeepIterator.prototype._pop = function () { |
| 12 | + assert(this._stack.length >= 1); |
| 13 | + assert(this._stack.length === this._level.length); |
| 14 | + let x = this._stack.pop(); |
| 15 | + let level = this._level.pop(); |
| 16 | + |
| 17 | + for (;;) { |
| 18 | + assert(this._stack.length === this._level.length); |
| 19 | + assert(Number.isInteger(level) && level >= 0); |
| 20 | + if (level === 0) return {done: false, value: x}; |
| 21 | + |
| 22 | + x = this._traverse(--level, x); |
| 23 | + } |
| 24 | +}; |
| 25 | + |
| 26 | +DeepIterator.prototype.next = function () { |
| 27 | + if (this._stack.length === 0) { |
| 28 | + /* eslint-disable no-fallthrough */ |
| 29 | + // eslint-disable-next-line default-case |
| 30 | + switch (this._direction) { |
| 31 | + case DOWNWARD: |
| 32 | + this._tree._middle = this._tree._middle._force(); |
| 33 | + if (this._tree._middle instanceof Deep) { |
| 34 | + this._treeStack.push(this._tree); |
| 35 | + this._tree = this._tree._middle; |
| 36 | + this._downwardStep(); |
| 37 | + ++this._currentLevel; |
| 38 | + this._level = this._stack.map(() => this._currentLevel); |
| 39 | + break; |
| 40 | + } else { |
| 41 | + this._direction = UPWARD; |
| 42 | + if (this._tree._middle instanceof Single) { |
| 43 | + this._stack = [this._tree._middle.a]; |
| 44 | + this._level = [this._currentLevel + 1]; |
| 45 | + break; |
| 46 | + } |
| 47 | + |
| 48 | + assert(this._tree._middle instanceof Empty); |
| 49 | + } |
| 50 | + |
| 51 | + case UPWARD: |
| 52 | + if (this._currentLevel === -1) return {done: true}; |
| 53 | + assert(this._tree instanceof Deep); |
| 54 | + this._upwardStep(); |
| 55 | + this._level = this._stack.map(() => this._currentLevel); |
| 56 | + |
| 57 | + this._tree = --this._currentLevel === -1 ? null : this._treeStack.pop(); |
| 58 | + } |
| 59 | + /* eslint-enable no-fallthrough */ |
| 60 | + } |
| 61 | + |
| 62 | + return this._pop(); |
| 63 | +}; |
| 64 | + |
| 65 | +DeepIterator.prototype[Symbol.iterator] = function () { |
| 66 | + return this; |
| 67 | +}; |
0 commit comments