Created
July 24, 2022 17:23
-
-
Save shovon/90a49519337d5bf6611ea7f68d657b1e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class Trie { | |
private children: Map<string, Trie> = new Map(); | |
insert(value: string) { | |
if (value === "") { | |
return; | |
} | |
const first = value[0]; | |
if (!first) { | |
throw new Error("Expected the first element to not be an empty string."); | |
} | |
const remainder = value.slice(1); | |
let node = this.children.get(first); | |
if (!node) { | |
node = new Trie(); | |
this.children.set(first, node); | |
} | |
node.insert(remainder); | |
} | |
has(value: string): boolean { | |
if (value === "") { | |
return this.children.size === 0; | |
} | |
const first = value[0]; | |
if (!first) { | |
throw new Error("Expected the first element to not be an empty string."); | |
} | |
const remainder = value.slice(1); | |
const node = this.children.get(first); | |
if (!node) { | |
return false; | |
} | |
return node.has(remainder); | |
} | |
} | |
function assert(assertion: boolean, message?: string) { | |
if (!assertion) { | |
throw new Error(message ?? "Failed"); | |
} | |
} | |
const trie = new Trie(); | |
trie.insert("cool"); | |
trie.insert("nice"); | |
trie.insert("sweet"); | |
trie.insert("amazing"); | |
trie.insert("haha"); | |
trie.insert("canada"); | |
assert(trie.has("cool")); | |
assert(trie.has("nice")); | |
assert(trie.has("sweet")); | |
assert(trie.has("amazing")); | |
assert(!trie.has("bmazing")); | |
assert(!trie.has("nmazing")); | |
assert(!trie.has("cmazing")); | |
assert(!trie.has("amazin")); | |
assert(!trie.has("mazing")); | |
assert(!trie.has("foo")); | |
assert(trie.has("haha")); | |
assert(trie.has("canada")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment