@datastructures-js/trie
Trie implementation in javascript. Each Trie node holds one character of a word.
Trie
Table of Contents
Installnpm install --save @datastructures-js/trie API requireconst Trie = require ( '@datastructures-js/trie' ) ; importimport Trie from '@datastructures-js/trie' ; Construction
const englishLang = new Trie ( ) ; .insert(word)insert a string word into the trie.
params
name type
word string
runtime
O(k) : k = length of the word
ExampleenglishLang. insert ( 'hi' ) ;
englishLang. insert ( 'hit' ) ;
englishLang. insert ( 'hide' ) ;
englishLang. insert ( 'hello' ) ;
englishLang. insert ( 'sand' ) ;
englishLang. insert ( 'safe' ) ;
englishLang. insert ( 'noun' ) ;
englishLang. insert ( 'name' ) ; Note: the empty string is not a default word in the trie. You can add the empty word explicitly using .insert('')
.has(word)checks if a word exists in the trie.
params
name type
word string
runtime
O(k) : k = length of the word
ExampleenglishLang. has ( 'hi' ) ;
englishLang. has ( 'sky' ) ; .find(word)finds a word in the trie and returns the node of its last character.
params
name type
word string
runtime
O(k) : k = length of the word
Exampleconst hi = englishLang. find ( 'hi' ) ;
const safe = englishLang. find ( 'safe' ) ;
.remove(word)removes a word from the trie.
params
name type
word string
runtime
O(k) : k = length of the word
ExampleenglishLang. remove ( 'hi' ) ;
englishLang. remove ( 'sky' ) ; .forEach(cb)traverses all words in the trie.
params
name type description
cb function called with each word in the trie
runtime
O(n) : n = number of nodes in the trie
englishLang. forEach ( ( word ) => console. log ( word) ) ;
.toArray()converts the trie into an array of words.
return description
array a list of all the words in the trie
runtime
O(n) : n = number of nodes in the trie
Exampleconsole. log ( englishLang. toArray ( ) ) ;
.wordsCount()gets the count of words in the trie.
Exampleconsole. log ( englishLang. wordsCount ( ) ) ; .nodesCount()gets the count of nodes in the trie.
Exampleconsole. log ( englishLang. nodesCount ( ) ) ; .clear()clears the trie.
ExampleenglishLang. clear ( ) ;
console. log ( englishLang. wordsCount ( ) ) ;
console. log ( englishLang. nodesCount ( ) ) ; TrieNode .getChar()returns the node's char.
.getParent()returns the parent node.
.isEndOfWord()check if a node is an end of a word.
.getChild(char)returns the child node of a char.
.hasChild(char)check the node has a child char.
.childrenCount()returns the number of children nodes.
Buildgrunt build
LicenseThe MIT License. Full License is here