Last active
August 9, 2023 16:27
-
-
Save sebinsua/d93eab10a09114c7665a689b88615f7c to your computer and use it in GitHub Desktop.
I experimented a little bit with tries.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class TrieNode { | |
public children: Record<string, TrieNode> = {}; | |
public isEndOfWord = false; | |
} | |
export class Trie { | |
private root: TrieNode; | |
constructor() { | |
this.root = new TrieNode(); | |
} | |
add(word: string) { | |
let node = this.root; | |
for (const char of word) { | |
if (!node.children[char]) { | |
node.children[char] = new TrieNode(); | |
} | |
node = node.children[char]; | |
} | |
node.isEndOfWord = true; | |
} | |
has(word: string) { | |
let searchSpace = [this.root]; | |
for (const char of word) { | |
searchSpace = | |
char === "*" | |
? searchSpace.flatMap((node) => Object.values(node.children)) | |
: searchSpace.flatMap((node) => | |
node.children[char] ? [node.children[char]] : [] | |
); | |
if (searchSpace.length === 0) { | |
return false; | |
} | |
} | |
return searchSpace.some((node) => node.isEndOfWord); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Much more interesting
Trie
which allows you to autocomplete from a prefix to find potential matching words, supports related words, and allows you to delete items to prune the tree.