lgrthms
Version:
Algorithms and data structures for your JavaScript and TypeScript projects 🧑💻
94 lines (93 loc) • 2.8 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Trie = void 0;
class Trie {
constructor() {
this.root = {};
this.endSymbol = '***';
this._size = 0;
}
get size() {
return this._size;
}
// O(n) time | O(n) space — where n is is the length of the string
insert(string) {
let node = this.root;
for (const char of string) {
if (node[char] === undefined) {
node[char] = {};
}
node = node[char];
}
node[this.endSymbol] = string;
this._size++;
return this._size;
}
// O(n) time | O(1) space — where n is is the length of the string
contains(string) {
let node = this.root;
for (const char of string) {
if (node[char] === undefined) {
return false;
}
node = node[char];
}
return node[this.endSymbol] !== undefined;
}
// O(n) time | O(n space) — where n is is the length of the string
remove(string) {
this._remove(string, 0, this.root);
}
// O(m) time | O(n) space — where
// m is the total number of characters in the trie
// n is the length of the longest word
autocomplete(string, limit = Infinity) {
let node = this.root;
for (const char of string) {
if (node[char] === undefined) {
return [];
}
node = node[char];
}
return this._getWords(node, [], limit);
}
// O(m) time | O(n) space — where
// m is the total number of characters in the trie
// n is the length of the longest word
getWords() {
return this._getWords(this.root, [], Infinity);
}
_remove(string, index, node) {
if (index === string.length) {
if (node[this.endSymbol] === undefined) {
return false;
}
delete node[this.endSymbol];
this._size--;
return Object.keys(node).length === 0;
}
const char = string[index];
if (node[char] === undefined) {
return false;
}
const canRemove = this._remove(string, index + 1, node[char]);
if (canRemove) {
delete node[char];
}
return Object.keys(node).length === 0;
}
_getWords(node, array, limit) {
for (const char in node) {
if (array.length === limit) {
break;
}
if (char === this.endSymbol) {
array.push(node[this.endSymbol]);
continue;
}
this._getWords(node[char], array, limit);
}
return array;
}
}
exports.Trie = Trie;