Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 832 of the free egghead.io lessons, plus get JavaScript content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Just one more step!

Check your inbox for an email from us and click link to unlock your lesson.



Search more efficiently with tries using Natural

1:40 JavaScript lesson by

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.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?