es-next-tools
Version:
A comprehensive utility library for JavaScript and TypeScript that provides a wide range of functions for common programming tasks, including mathematical operations, date manipulations, array and object handling, string utilities, and more.
43 lines (42 loc) • 1.06 kB
JavaScript
/**
* Represents a node in a Trie.
*/
class TrieNode {
children = new Map();
isEndOfWord = false;
}
/**
* Represents a Trie (prefix tree).
*/
export class Trie {
root = new TrieNode();
/**
* Inserts a word into the Trie.
* @param {string} word - The word to insert.
*/
insert(word) {
let current = this.root;
for (const char of word) {
if (!current.children.has(char)) {
current.children.set(char, new TrieNode());
}
current = current.children.get(char);
}
current.isEndOfWord = true;
}
/**
* Searches for a word in the Trie.
* @param {string} word - The word to search for.
* @returns {boolean} True if found, false otherwise.
*/
search(word) {
let current = this.root;
for (const char of word) {
if (!current.children.has(char)) {
return false;
}
current = current.children.get(char);
}
return current.isEndOfWord;
}
}