TreeIterator.js 1.9 KB

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