Trie implementation in javascript. Each Trie node holds one character of a word.
Trie
npm install --save @datastructures-js/trie
const { Trie, TrieNode } = require ( '@datastructures-js/trie' ) ;
import { Trie , TrieNode } from '@datastructures-js/trie' ;
const dictionary = new Trie ( ) ;
insert the string form of value (value.toString()
) into the trie.
Note: the empty string is not a default word in the trie. empty word can be added by explicitly calling .insert('')
params
return
runtime
value: any
Trie
O(k): k = length of string value
dictionary
. insert ( 'hi' )
. insert ( 'hit' )
. insert ( 'hide' )
. insert ( 'hello' )
. insert ( 'sand' )
. insert ( 'safe' )
. insert ( 'noun' )
. insert ( 'name' ) ;
checks if a word exists in the trie.
params
return
runtime
value: any
boolean
O(k): k = length of string value
dictionary . has ( 'hi' ) ; // true
dictionary . has ( 'sky' ) ; // false
finds a word in the trie and returns the node of its last character.
params
return
runtime
value: any
TrieNode
O(k): k = length of string value
const hi = dictionary . find ( 'hi' ) ;
// hi.getChar() = 'i'
// hi.getParent().getChar() = 'h'
const safe = dictionary . find ( 'safe' ) ;
// safe.getChar() = 'e'
// safe.getParent().getChar() = 'f'
// safe.getParent().getParent().getChar() = 'a'
const nothing = dictionary . find ( 'nothing' ) ; // null
removes a word from the trie.
params
return
runtime
value: any
string: the removed word
O(k): k = length of string value
dictionary . remove ( 'hi' ) ; // hi
// none existing word
dictionary . remove ( 'sky' ) ; // null
traverses all words in the trie.
params
runtime
cb: function
O(n): n = number of nodes in the trie
dictionary . forEach ( ( word ) => console . log ( word ) ) ;
/*
hit
hide
hello
sand
safe
noun
name
*/
converts the trie into an array of words.
return
runtime
array<string>
O(n): n = number of nodes in the trie
console . log ( dictionary . toArray ( ) ) ;
// ['hit', 'hide', 'hello', 'sand', 'safe', 'noun', 'name']
gets the count of words in the trie.
return
runtime
number
O(1)
console . log ( dictionary . wordsCount ( ) ) ; // 7
gets the count of nodes in the trie.
return
runtime
number
O(1)
console . log ( dictionary . nodesCount ( ) ) ; // 23
clears the trie.
dictionary . clear ( ) ;
console . log ( dictionary . wordsCount ( ) ) ; // 0
console . log ( dictionary . nodesCount ( ) ) ; // 1
converts an existing array of values into a trie.
params
return
runtime
list: array<any>
boolean
O(n * k)
const numbersTrie = Trie . fromArray ( [ 1 , 32 , 123 , 21 , 222 , 132 , 111 , 312 ] ) ;
console . log ( numbersTrie . wordsCount ( ) ) ; // 8
console . log ( numbersTrie . has ( '132' ) ) ; // true
console . log ( numbersTrie . has ( 123 ) ) ; // true
params
trieNode: TrieNode
.setEndOfWord(isEndOfWord)
params
isEndOfWord: boolean
params return
char: string TrieNode
params return
char: string boolean
The MIT License. Full License is here