Autocomplete using Tries
In this article, I’m going over creating an autocompletion/prediction system using a data-structure called Trie, it’s fast and easy to customize.
Trie is a simple data-structure most commonly used as a dictionary, it looks like so:
As you see, it’s just a tree, a set of nodes connected to other [child] nodes, but the nodes have a special relationship:
Each child node extends it’s parent with one extra character.
It’s pretty easy to traverse this tree and predict the next possible words.
We’re going to use ES6 classes to create our
Let’s start with our simple Node class:
Unlike binary trees where each node has a left and right child, Trie nodes don’t necessarily have a limit on how many children they can have.
Every Trie must have a root node with empty value, that’s how our single-character nodes follow the rule of Tries.
Ok, our first method,
add handles adding a value to the trie, creating necessary parent nodes for our value.
At each iteration, we compare the
ith character of our value, with
ith character of current node’s children’s value,
if we find one, we continue to search the next branch, else, we create a node with
value.slice(0, i + 1) and move onto the created node.
It might be a little hard to grasp at first, so I created a visualization of this method to help you understand it easier, take a look: Trie Visualization
Then we have our find method, which searches for the given value in the trie. The algorithm for searching is the same, comparing by index and moving to the next branch.
That’s it for our simple Trie class, now let’s create an actual input with autocomplete functionality using our Trie.
I put some random names and stuff into three categories, results: data.json
Now we have to create a Trie of our data:
As simple as that, our trie is made, it looks like this: Data
Now, let’s actually show results:
Autocomplete 1 This will only show the instant-childs of the word entered, but that’s not what we want, we want to show complete words, how do we do that?
First, we need a way to detect complete words, we can have a flag to recognize complete words, we can modify our
add method to
automatically flag whole words or we can manually add the flag after adding the node, as we did by setting a category for our words,
so we already have a flag to recognize whole words, that’s our
category property, now let’s add a new method to our Trie class to find
And change our event listener like so:
Autocomplete 2 Ta-daa!
We have our autocomplete working! Let’s add zsh-like-tab-to-next-char functionality.
That’s it! We have an input with autocomplete and tab-to-next-char. Isn’t it awesome?
Pst! I have a repository of algorithm implementations in ES6, you might want to take a look! mdibaiee/harmony-algorithms