@datastructures-js/trie
Trie implementation in javascript. Each Trie node holds one character of a word.
Contents
Install
npm install --save @datastructures-js/trie
require
const { Trie, TrieNode } = require('@datastructures-js/trie');
import
import { Trie, TrieNode } from '@datastructures-js/trie';
API
constructor
const dictionary = new Trie();
insert
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('')
dictionary
.insert('hi')
.insert('hit')
.insert('hide')
.insert('hello')
.insert('sand')
.insert('safe')
.insert('noun')
.insert('name');
has
checks if a word exists in the trie.
dictionary.has('hi');
dictionary.has('sky');
find
finds a word in the trie and returns the node of its last character.
const hi = dictionary.find('hi');
const safe = dictionary.find('safe');
const nothing = dictionary.find('nothing');
remove
removes a word from the trie.
dictionary.remove('hi');
dictionary.remove('sky');
forEach
traverses all words in the trie.
dictionary.forEach((word) => console.log(word));
toArray
converts the trie into an array of words.
console.log(dictionary.toArray());
wordsCount
gets the count of words in the trie.
console.log(dictionary.wordsCount());
nodesCount
gets the count of nodes in the trie.
console.log(dictionary.nodesCount());
clear
clears the trie.
dictionary.clear();
console.log(dictionary.wordsCount());
console.log(dictionary.nodesCount());
Trie.fromArray
converts an existing array of values into a trie.
const numbersTrie = Trie.fromArray([1, 32, 123, 21, 222, 132, 111, 312]);
console.log(numbersTrie.wordsCount());
console.log(numbersTrie.has('132'));
console.log(numbersTrie.has(123));
TrieNode
isRoot()
checks if node is root.
isLeaf()
checks if has no children.
getChar()
gets the node's char.
getParent()
gets the node's parent node.
setParent(node: TrieNode)
sets the node's parent node.
isEndOfWord()
checks if node's char is last in a word.
setEndOfWord(endOfWord: boolean)
sets if node's char is last in a word.
getChild(char: string)
gets the node's child from a char.
hasChild(char: string)
checks if the node has a child from a char.
childrenCount()
gets the node's children count.
Build
grunt build
License
The MIT License. Full License is here