Published
Edited
Dec 12, 2021
2 stars
Insert cell
# Trie
Insert cell
trie = new Trie();
Insert cell
{
trie.insert('cat');
trie.insert('can');
trie.insert('cap');
}
Insert cell
trie.has('cat')
Insert cell
trie.has('can')
Insert cell
trie.has('capp')
Insert cell
class Node {
constructor(value = "") {
this.value = value;
this.children = new Map();
}
}
Insert cell

class Trie {
constructor() {
this.root = new Node();
}

insert(string) {
let currentNode = this.root;

for (const char of string) {
if (!currentNode.children.has(char)) {
currentNode.children.set(char, new Node(currentNode.value + char));
}
currentNode = currentNode.children.get(char);
}
}

has(string) {
let currentNode = this.root;
for (const char of string) {
if (!currentNode.children.has(char)) {
return false;
}
currentNode = currentNode.children.get(char);
}
return true;
}
}

Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more