TreeIterator.js
1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
'use strict';
const TREE = Symbol();
const ROOT = Symbol();
const NEXT = Symbol();
const ITERATE_FUNC = Symbol();
class TreeIterator {
constructor(tree, root, firstResult, iterateFunction) {
this[TREE] = tree;
this[ROOT] = root;
this[NEXT] = firstResult;
this[ITERATE_FUNC] = iterateFunction;
}
next() {
const tree = this[TREE];
const iterateFunc = this[ITERATE_FUNC];
const root = this[ROOT];
if (!this[NEXT]) {
return {
done: true,
value: root,
};
}
const value = this[NEXT];
if (iterateFunc === 1) {
this[NEXT] = tree._node(value).previousSibling;
}
else if (iterateFunc === 2) {
this[NEXT] = tree._node(value).nextSibling;
}
else if (iterateFunc === 3) {
this[NEXT] = tree._node(value).parent;
}
else if (iterateFunc === 4) {
this[NEXT] = tree.preceding(value, {root: root});
}
else /* if (iterateFunc === 5)*/ {
this[NEXT] = tree.following(value, {root: root});
}
return {
done: false,
value: value,
};
}
}
Object.defineProperty(TreeIterator.prototype, Symbol.iterator, {
value: function() {
return this;
},
writable: false,
});
TreeIterator.PREV = 1;
TreeIterator.NEXT = 2;
TreeIterator.PARENT = 3;
TreeIterator.PRECEDING = 4;
TreeIterator.FOLLOWING = 5;
Object.freeze(TreeIterator);
Object.freeze(TreeIterator.prototype);
module.exports = TreeIterator;