abstract_trie_node.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { Debugger } from '../common/debugger.js';
  2. import { TrieNodeKind } from './trie_node.js';
  3. export class AbstractTrieNode {
  4. constructor(constraint, test) {
  5. this.constraint = constraint;
  6. this.test = test;
  7. this.children_ = {};
  8. this.kind = TrieNodeKind.ROOT;
  9. }
  10. getConstraint() {
  11. return this.constraint;
  12. }
  13. getKind() {
  14. return this.kind;
  15. }
  16. applyTest(object) {
  17. return this.test(object);
  18. }
  19. addChild(node) {
  20. const constraint = node.getConstraint();
  21. const child = this.children_[constraint];
  22. this.children_[constraint] = node;
  23. return child;
  24. }
  25. getChild(constraint) {
  26. return this.children_[constraint];
  27. }
  28. getChildren() {
  29. const children = [];
  30. for (const val of Object.values(this.children_)) {
  31. children.push(val);
  32. }
  33. return children;
  34. }
  35. findChildren(object) {
  36. const children = [];
  37. for (const val of Object.values(this.children_)) {
  38. if (val.applyTest(object)) {
  39. children.push(val);
  40. }
  41. }
  42. return children;
  43. }
  44. removeChild(constraint) {
  45. delete this.children_[constraint];
  46. }
  47. toString() {
  48. return this.constraint;
  49. }
  50. }
  51. export class StaticTrieNode extends AbstractTrieNode {
  52. constructor(constraint, test) {
  53. super(constraint, test);
  54. this.rule_ = null;
  55. this.kind = TrieNodeKind.STATIC;
  56. }
  57. getRule() {
  58. return this.rule_;
  59. }
  60. setRule(rule) {
  61. if (this.rule_) {
  62. Debugger.getInstance().output('Replacing rule ' + this.rule_ + ' with ' + rule);
  63. }
  64. this.rule_ = rule;
  65. }
  66. toString() {
  67. const rule = this.getRule();
  68. return rule
  69. ? this.constraint + '\n' + '==> ' + this.getRule().action
  70. : this.constraint;
  71. }
  72. }