Tries are a data structure that provide an efficient way to search for the existence of a word or phrase in a body of text, or to search by prefix.
First, import the natural library. To make a new trie structure, the syntax is new natural.Trie. By default, tries are case sensitive. If you don't want that to be the case, you can pass in false here. But for this example, we do want it to be case sensitive.
Next, we need some data. To create the trie structure, we need to add all of these strings to the trie by saying "trie.addString." One of the simplest things we can do with trie is look to see if a string is contained in the trie.
To do that, we say trie.contains a string. We can see that that's true. We can also words starting with a specific prefix by saying trie.keysWithPrefix, and then the prefix. If we search for "cr," we'll get crane, creeper, crossbill and crow back.
We can also see if any of the words in trie match a prefix of a word by saying trie.findMatchesOnPath, that's the search path they're referring to. We'll say, "cuckoohead." We can see that cuckoo matches the prefix.