Public
Edited
Dec 18
Insert cell
Insert cell
Insert cell
{
const words = [
"apple",
"app",
"application",
"apricot",
"banana",
"band",
"bandage",
"cat",
"caterpillar",
"dog",
"dodge",
"elephant"
];

const trie = new Trie(words);

// Event handler
const onChange = (e) => {
const currentOptions = e.target.value ? trie.search(e.target.value) : [];
render(currentOptions);
};

// Main container
const container = htl.html`
<div style="font-family: sans-serif; margin: 8px;">
<input
placeholder="Type here..."
style="padding: 8px; width: 200px; margin-bottom: 8px;"
oninput=${onChange} />
<div id="results"></div>
</div>`;

// Render function to update results
const render = (currentOptions) => {
const resultsContainer = container.querySelector("#results");
resultsContainer.innerHTML = ""; // Clear previous results
currentOptions.forEach((option) => {
const div = htl.html`<div style="padding: 4px; cursor: pointer;">
${option}
</div>`;
resultsContainer.appendChild(div);
});
};

return container;
}
Insert cell
trie = new Trie([
"apple",
"app",
"application",
"apricot",
"banana",
"band",
"bandage",
"cat",
"caterpillar",
"dog",
"dodge",
"elephant"
]);
Insert cell
class Trie {
constructor(words) {
this.root = new TrieNode();

// Fill the trie if words are specified
if (words) {
words.forEach(w => this.insert(w))
}
}

insert(word) {
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;
}

search(prefix) {
let node = this.root;

for (const char of prefix) {
if (node.children[char]) {
node = node.children[char];
} else {
return []
}
}

return this._getWords(node, prefix)
}

getOptions() {
return this._getWords(this.root, "")
}

_getWords(node, prefix) {
let words = [];

if (node.isEndOfWord) {
words.push(prefix);
}

for (const [key, childNode] of Object.entries(node.children)) {
words.push(...this._getWords(childNode, prefix + key))
}

return words
}
}
Insert cell
class TrieNode {
constructor() {
this.children = {};
this.isEndOfWord = false;
}
}
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