trie.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /**
  2. * Suffix Trie based on Mnemonist Trie
  3. */
  4. const SENTINEL = String.fromCharCode(0);
  5. class Trie {
  6. size = 0;
  7. root = {};
  8. /**
  9. * Method used to add the given prefix to the trie.
  10. *
  11. * @param {string} suffix - Prefix to follow.
  12. * @return {Trie}
  13. */
  14. add(suffix) {
  15. let node = this.root;
  16. let token;
  17. for (let i = suffix.length - 1; i >= 0; i--) {
  18. token = suffix[i];
  19. node = node[token] || (node[token] = {});
  20. }
  21. // Do we need to increase size?
  22. if (!(SENTINEL in node)) this.size++;
  23. node[SENTINEL] = true;
  24. return this;
  25. }
  26. /**
  27. * Method used to retrieve every item in the trie with the given prefix.
  28. *
  29. * @param {string} suffix - Prefix to query.
  30. * @param {boolean} [includeEqualWithSuffix]
  31. * @return {string[]}
  32. */
  33. find(suffix, includeEqualWithSuffix = true) {
  34. let node = this.root;
  35. const matches = [];
  36. let token;
  37. let i;
  38. let l;
  39. for (let i = suffix.length - 1; i >= 0; i--) {
  40. token = suffix[i];
  41. node = node[token];
  42. if (node == null) return matches;
  43. }
  44. // Performing DFS from prefix
  45. const nodeStack = [node];
  46. const suffixStack = [suffix];
  47. let k;
  48. let $suffix = suffix;
  49. while (nodeStack.length) {
  50. $suffix = suffixStack.pop();
  51. node = nodeStack.pop();
  52. for (k in node) {
  53. if (k === SENTINEL) {
  54. if (includeEqualWithSuffix) {
  55. matches.push($suffix);
  56. } else if ($suffix !== suffix) {
  57. matches.push($suffix);
  58. }
  59. continue;
  60. }
  61. nodeStack.push(node[k]);
  62. suffixStack.push(k + $suffix);
  63. }
  64. }
  65. return matches;
  66. }
  67. toJSON() {
  68. return this.root;
  69. }
  70. /**
  71. * Method used to clear the trie.
  72. *
  73. * @return {void}
  74. */
  75. // clear() {
  76. // // Properties
  77. // this.root = {};
  78. // this.size = 0;
  79. // }
  80. /**
  81. * Method used to update the value of the given prefix in the trie.
  82. *
  83. * @param {string|array} prefix - Prefix to follow.
  84. * @param {(oldValue: any | undefined) => any} updateFunction - Update value visitor callback.
  85. * @return {Trie}
  86. */
  87. // update(prefix, updateFunction) {
  88. // let node = this.root;
  89. // let token;
  90. // for (let i = 0, l = prefix.length; i < l; i++) {
  91. // token = prefix[i];
  92. // node = node[token] || (node[token] = {});
  93. // }
  94. // // Do we need to increase size?
  95. // if (!(SENTINEL in node))
  96. // this.size++;
  97. // node[SENTINEL] = updateFunction(node[SENTINEL]);
  98. // return this;
  99. // }
  100. /**
  101. * Method used to delete a prefix from the trie.
  102. *
  103. * @param {string|array} suffix - Prefix to delete.
  104. * @return {boolean}
  105. */
  106. delete(suffix) {
  107. let node = this.root;
  108. let toPrune = null;
  109. let tokenToPrune = null;
  110. let parent;
  111. let token;
  112. for (let i = suffix.length - 1; i >= 0; i--) {
  113. token = suffix[i];
  114. parent = node;
  115. node = node[token];
  116. // Prefix does not exist
  117. if (typeof node === 'undefined')
  118. return false;
  119. // Keeping track of a potential branch to prune
  120. if (toPrune !== null) {
  121. if (Object.keys(node).length > 1) {
  122. toPrune = null;
  123. tokenToPrune = null;
  124. }
  125. }
  126. else {
  127. if (Object.keys(node).length < 2) {
  128. toPrune = parent;
  129. tokenToPrune = token;
  130. }
  131. }
  132. }
  133. if (!(SENTINEL in node)) return false;
  134. this.size--;
  135. if (toPrune) {
  136. delete toPrune[tokenToPrune];
  137. } else {
  138. delete node[SENTINEL];
  139. }
  140. return true;
  141. }
  142. /**
  143. * Method used to assert whether the given prefix exists in the Trie.
  144. *
  145. * @param {string} suffix - Prefix to check.
  146. * @return {boolean}
  147. */
  148. has(suffix) {
  149. let node = this.root;
  150. let token;
  151. for (let i = suffix.length - 1; i >= 0; i--) {
  152. token = suffix[i];
  153. node = node[token];
  154. if (typeof node === 'undefined')
  155. return false;
  156. }
  157. return SENTINEL in node;
  158. }
  159. /**
  160. * Method returning an iterator over the trie's prefixes.
  161. *
  162. * @param {string|array} [prefix] - Optional starting prefix.
  163. * @return {Iterator}
  164. */
  165. // prefixes(prefix) {
  166. // let node = this.root;
  167. // const nodeStack = [];
  168. // const prefixStack = [];
  169. // let token;
  170. // let i;
  171. // let l;
  172. // const isString = this.mode === 'string';
  173. // // Resolving initial prefix
  174. // if (prefix) {
  175. // for (i = 0, l = prefix.length; i < l; i++) {
  176. // token = prefix[i];
  177. // node = node[token];
  178. // // If the prefix does not exist, we return an empty iterator
  179. // if (typeof node === 'undefined')
  180. // return Iterator.empty();
  181. // }
  182. // }
  183. // else {
  184. // prefix = isString ? '' : [];
  185. // }
  186. // nodeStack.push(node);
  187. // prefixStack.push(prefix);
  188. // return new Iterator(() => {
  189. // let currentNode;
  190. // let currentPrefix;
  191. // let hasValue = false;
  192. // let k;
  193. // while (nodeStack.length) {
  194. // currentNode = nodeStack.pop();
  195. // currentPrefix = prefixStack.pop();
  196. // for (k in currentNode) {
  197. // if (k === SENTINEL) {
  198. // hasValue = true;
  199. // continue;
  200. // }
  201. // nodeStack.push(currentNode[k]);
  202. // prefixStack.push(isString ? currentPrefix + k : currentPrefix.concat(k));
  203. // }
  204. // if (hasValue)
  205. // return { done: false, value: currentPrefix };
  206. // }
  207. // return { done: true };
  208. // });
  209. // }
  210. /**
  211. * Convenience known methods.
  212. */
  213. // inspect() {
  214. // const proxy = new Set();
  215. // const iterator = this.prefixes();
  216. // let step;
  217. // while ((step = iterator.next(), !step.done))
  218. // proxy.add(step.value);
  219. // // Trick so that node displays the name of the constructor
  220. // Object.defineProperty(proxy, 'constructor', {
  221. // value: Trie,
  222. // enumerable: false
  223. // });
  224. // return proxy;
  225. // }
  226. /**
  227. * Static .from function taking an arbitrary iterable & converting it into
  228. * a trie.
  229. *
  230. * @param {string[]} iterable - Target iterable.
  231. * @return {Trie}
  232. */
  233. static from = iterable => {
  234. const trie = new Trie();
  235. iterable.forEach(i => trie.add(i));
  236. return trie;
  237. };
  238. }
  239. /**
  240. * Exporting.
  241. */
  242. module.exports.SENTINEL = SENTINEL;
  243. module.exports = Trie;