Trie Prefix Tree
This is a Trie implementation written in JavaScript, with insert and remove capability. It can be used to search a predefined dictionary for prefixes, check a prefix exists and retrieve a list of anagrams and sub-anagrams based on given letters.
What is a Trie?
A Trie (also known as a prefix-tree) is a data structure for storing strings in a tree. Each branch in the tree represents a single character which allows for fast and efficient depth-first searching. Let's say we have a dictionary with the words: CAR, CAT and CURL. We can visualise the trie like this:
Installation
Pull down dependencies:
npm install
This project uses Jest for unit testing and ESLint for linting.
To run combined linting & unit tests:
npm test
To run linting:
npm run lint
Run tests in watch mode:
npm run test-watch
Get code coverage report:
npm run test-coverage
How to Use
To use the Trie, install and save it to your package dependencies:
npm install trie-prefix-tree --save
To create a new Trie:
var trie = require('trie-prefix-tree');
import trie from 'trie-prefix-tree';
Instantiate the Trie:
var myTrie = trie(['cat', 'cats', 'dogs', 'elephant', 'tiger']);
Trie functionality:
myTrie.dump();
myTrie.dump(2);
myTrie.addWord('lion');
myTrie.removeWord('dogs');
Adding and removing words can be chained:
myTrie.addWord('hello').removeWord('hello');
Prefix searching:
myTrie.isPrefix('do');
myTrie.isPrefix('z');
myTrie.countPrefix('c');
myTrie.getPrefix('c');
myTrie.getPrefix('c', false);
Other:
myTrie.getWords();
myTrie.getWords(false);
myTrie.hasword('elephant');
myTrie.hasWord('zoo');
myTrie.getAnagrams('act');
myTrie.getSubAnagrams('ctalion'); ['cat', 'cats', 'lion'];
Credits
Credit goes to Kent C. Dodds for providing the awesome 'How to Create an Open Source JavaScript Library' course, available on egghead.io.
License
This project is referenced under the MIT license and is free to use and distribute.
MIT @ Lyndsey Browning