Published
Edited
Nov 4, 2021
1 star
Insert cell
Insert cell
Insert cell
md`${
testWord // don't show anything if there is no input
? findSuffixes(testWord, maxLength).join(", ")
: ""
}`
Insert cell
function findSuffixes(word, maxLength) {
word = word.toLowerCase();
let node = words_trie;
for (const char of word) {
let nextNode = node[char];
// if our word isn't in the dictionary, we
if (!nextNode) return [""];
node = nextNode;
}
let words = findChildren(node, word, [], maxLength);
return words;
}
Insert cell
maxLength = 10
Insert cell
function findChildren(node, word, list, maxLength) {
if (node.__ === 1) list.push(word);
for (const char in node) {
findChildren(node[char], word + char, list, maxLength);
// no need to search the whole trie if we're
// already at the max length of our results list
if (list.length >= maxLength) return list;
}
return list;
}
Insert cell
words_trie = {
const root = {};
// generate trie from each word
for (const word of words_list) {
let node = root;
// for each character in the word, either advance
// into the existing matching node, or if no
// matching character node is in the trie yet,
// create the node and avance into that
for (const char of word) {
let nextNode = node[char];
if (!nextNode) {
node[char] = nextNode = {};
}
node = nextNode;
}
node.__ = 1; // mark the nodes that are endings of real words
}
return root;
}
Insert cell
words_list = {
const words_string = await words.text();
return words_string.split("\r\n");
}
Insert cell
words = FileAttachment("words_alpha.txt")
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