@figliolia/data-structures
Version:
Efficient data structures for every day programming
76 lines (75 loc) • 1.87 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Trie = void 0;
/**
* Trie
*
* A graph-like data structure for optimized search over multiple
* strings
*
* ```typescript
* import { Trie } from "@figliolia/data-structures";
*
* const dictionary = new Trie();
* dictionary.add("hello");
* dictionary.add("goodbye");
* dictionary.add("helpful");
* dictionary.search("hello"); // true
* dictionary.search("help", false); // true
* ```
*/
class Trie {
constructor(value) {
this.isWord = false;
this.dictionary = {};
this.value = value;
}
/**
* Add
*
* Adds a word to the current Trie
*/
add(value, root = this) {
let current = root;
for (const char of value) {
if (!current.hasAdjacent(char)) {
current.dictionary[char] = new Trie(char);
}
current = current.get(char);
}
current.isWord = true;
}
/**
* Search
*
* Searches for a word in the current Trie. Specifying `Trie.search(word, false)` allows
* you to search for prefixes within multiple words in the Trie
*/
search(value, isWord = true, root = this) {
let current = root;
for (const char of value) {
if (!current.hasAdjacent(char)) {
return false;
}
current = current.get(char);
}
return isWord ? current.isWord : true;
}
/**
* Has Adjacent
*
* Returns true a if the provided character proceeds the current Trie
*/
hasAdjacent(value) {
return value in this.dictionary;
}
/**
* Get
*
* Returns a reference to a Trie with the provided character
*/
get(value) {
return this.dictionary[value];
}
}
exports.Trie = Trie;