Giter Club home page Giter Club logo

trie-prefix-tree's Introduction

Trie Prefix Tree

Travis Build codecov coverage version downloads MIT License semantic-release

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:

trie data structure

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');

// using ES2015 Modules
import trie from 'trie-prefix-tree';

Instantiate the Trie:

var myTrie = trie(['cat', 'cats', 'dogs', 'elephant', 'tiger']);

Trie functionality:

// retrieve a stringified dump of the Trie object
myTrie.dump(); // { c: { a: { t: $: 1 }, s: 1 ... }}

// optionally pass in spacer parameter to format the output string
myTrie.dump(2); // equivalent of JSON.stringify(obj, null, 2);
// retrieve the Trie object instance
myTrie.tree();
// add a new word to the Trie
myTrie.addWord('lion');
// remove an existing word from the Trie
myTrie.removeWord('dogs');

Adding and removing words can be chained:

myTrie.addWord('hello').removeWord('hello');

Prefix searching:

// check if a prefix exists:
myTrie.isPrefix('do'); // true
myTrie.isPrefix('z'); // false
// count prefixes
myTrie.countPrefix('c'); // 2
// get an array of words with the passed in prefix
myTrie.getPrefix('c'); // ['cat', 'cats']

// Pass false as the second parameter to disable 
// output being sorted alphabetically
// this is useful when your dictionary is already sorted
// and will therefore save performance
myTrie.getPrefix('c', false); // ['cat', 'cats']
// get a random word at a prefix
myTrie.getRandomWordWithPrefix('c'); // 'cat'
myTrie.getRandomWordWithPrefix('c'); // 'cats'

Other:

// retrieve a full list of words in the Trie
// the output array is automatically sorted
myTrie.getWords(); // ['cat', 'cats', 'elephant', 'lion', 'tiger']

// pass false to disable the output being sorted
// this is useful when your dictionary is already sorted
// and will therefore save performance
myTrie.getWords(false); // ['cat', 'cats', 'elephant', 'tiger', 'lion']
// check if a word exists in the Trie
myTrie.hasWord('elephant'); // true
myTrie.hasWord('zoo'); // false
// generate a list of valid anagrams from the given letters
myTrie.getAnagrams('act'); // ['cat'];
// generate a list of valid sub-anagrams from the given letters
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

trie-prefix-tree's People

Contributors

arjunmehta avatar fzembow avatar lyndseybrowning avatar zhuangya avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

trie-prefix-tree's Issues

Feature request: get random word at prefix

Hi!

Thanks for this helpful library, useful when thinking of how to make word games :)

I'm interested in picking a random word at a prefix. I know that it's possible to do by first trie.getPrefix(prefix) and then pick randomly from that array, but it seems inefficient given that it doesn't take advantage of the underlying trie structure.

Expose the actual tree object for the instance

It would be great to have access to the actual tree produced
So in addition to myTree.dump(), something like myTrie.tree():

/**
 * Get a the generated trie-tree
*/
tree() {
  return trie;
},

This is useful in cases where there are large trees. I needed to crawl the tree, and the only way I could otherwise do that with this library would be to stringify then parse. However, that has memory implications.

Thoughts? I can create a pull request.

Add case sensitivity option or document case insensitivity

Love the library. However, it was a painful experience to find out that the trie match is case insensitive. It seems that our system has skipped many workloads over the years that happened to have a lowercase name. The cause was that the workload with the uppercase name had already ran previously.

Therefore, please, add a case sensitivity option. And if that is not possible, maybe document it visibly so that users know what to expect.

The culprit line seems to be: src/index.js#L46

There is also a pending PR #11 from another user that implements the feature.

Issues when word contains $

If I have something like

var triePrefixTree = require("trie-prefix-tree");

var allFunctionNames = triePrefixTree([]);

allFunctionNames.addWord("test$clone");

console.log(allFunctionNames.getPrefix("te"));

I get ["test", "test$clone"] even though I never added test.

Worse, if I do add test as below

var triePrefixTree = require("trie-prefix-tree");

var allFunctionNames = triePrefixTree([]);

allFunctionNames.addWord("test");
allFunctionNames.addWord("test$clone");

console.log(allFunctionNames.getPrefix("te"));

it produces an error: TypeError: Cannot create property 'c' on number '1'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.