mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2026-03-13 08:51:02 +08:00
68 lines
1.4 KiB
JavaScript
68 lines
1.4 KiB
JavaScript
import TrieNode from './TrieNode';
|
|
|
|
// Character that we will use for trie tree root.
|
|
const HEAD_CHARACTER = '*';
|
|
|
|
export default class Trie {
|
|
constructor() {
|
|
this.head = new TrieNode(HEAD_CHARACTER);
|
|
}
|
|
|
|
/**
|
|
* @param {string} word
|
|
* @return {Trie}
|
|
*/
|
|
addWord(word) {
|
|
const characters = Array.from(word);
|
|
let currentNode = this.head;
|
|
|
|
for (let charIndex = 0; charIndex < characters.length; charIndex += 1) {
|
|
const isComplete = charIndex === characters.length - 1;
|
|
currentNode = currentNode.addChild(characters[charIndex], isComplete);
|
|
}
|
|
|
|
return this;
|
|
}
|
|
|
|
/**
|
|
* @param {string} word
|
|
* @return {string[]}
|
|
*/
|
|
suggestNextCharacters(word) {
|
|
const lastCharacter = this.getLastCharacterNode(word);
|
|
|
|
if (!lastCharacter) {
|
|
return null;
|
|
}
|
|
|
|
return lastCharacter.suggestChildren();
|
|
}
|
|
|
|
/**
|
|
* @param {string} word
|
|
* @return {boolean}
|
|
*/
|
|
doesWordExist(word) {
|
|
return !!this.getLastCharacterNode(word);
|
|
}
|
|
|
|
/**
|
|
* @param {string} word
|
|
* @return {TrieNode}
|
|
*/
|
|
getLastCharacterNode(word) {
|
|
const characters = Array.from(word);
|
|
let currentNode = this.head;
|
|
|
|
for (let charIndex = 0; charIndex < characters.length; charIndex += 1) {
|
|
if (!currentNode.hasChild(characters[charIndex])) {
|
|
return null;
|
|
}
|
|
|
|
currentNode = currentNode.getChild(characters[charIndex]);
|
|
}
|
|
|
|
return currentNode;
|
|
}
|
|
}
|