Package Exports
- @kamilmielnik/trie
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@kamilmielnik/trie) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
@kamilmielnik/trie
Trie data structure implementation (in TypeScript). Highly performant. No dependencies. Built for a Scrabble Solver.
Installation
npm install @kamilmielnik/trie --save
Usage
import Trie from '@kamilmielnik/trie';
const trie = new Trie();
trie.add('master');
trie.add('mask');
console.log(trie.hasPrefix('man')); // false
console.log(trie.hasPrefix('mas')); // true
console.log(trie.has('mas')); // false
console.log(trie.remove('mas')); // false
console.log(trie.has('master')); // true
console.log(trie.serialize()); // "(m(a(s(t(e(r))k))))"
console.log(trie.remove('master')); // true
console.log(trie.serialize()); // "(m(a(s(k))))"
API
Trie
A class
representing the Trie data structure.
Import
import Trie from '@kamilmielnik/trie';
Static functions
Trie.deserialize(serialized: string): Trie
Creates a new
Trie
by deserializing givenstring
. The inverse ofTrie.prototype.serialize
.Trie.fromArray(words: string[]): Trie
Creates a new
Trie
based on array ofwords
.
Instance properties
root: Node;
Readonly property. Returns the root
Node
of theTrie
. It's not a copy. Mutate at your own risk.
Instance methods
Trie.prototype.add(word: string): Node
Inserts
word
into theTrie
. ReturnsNode
representing last character in the word.Trie.prototype.find(prefix: string): Node | undefined
Returns
Node
representing a givenprefix
. Returnsundefined
if there is no such Node.Trie.prototype.has(word: string): boolean
Returns
true
if givenword
is in theTrie
.Trie.prototype.hasPrefix(prefix: string): boolean
Returns
true
if there are any words with givenprefix
in theTrie
.Trie.prototype.remove(word: string): boolean
Removes word from the
Trie
if it exists. Returnstrue
ifword
was removed.Trie.prototype.traverse( callback: (parameters: { node: Node; prefix: string; } => boolean | void, options: { sort?: boolean } ): void
Visits every descendant
Node
in theTrie
and calls acallback
for each one. Returntrue
fromcallback
to stop traversing. Passsort: true
as an option to visit nodes in alphabetical order.Trie.prototype.serialize(): string
Converts
Trie
into a string. The inverse ofTrie.deserialize
.It serializes 41 MB Polish dictionary down to 12 MB (-71%).
It serializes 1.9 MB English (US) dictionary down to 993 KB (-48%).
It serializes 2.9 MB English (GB) dictionary down to 1.5 MB (-49%).
Node
It's a type (TypeScript-only).
import { Node } from '@kamilmielnik/trie';
Properties
[key: string]: Node
key
is a single character (string of length 1).wordEnd?: true
Indicates that keys of all parent nodes make a valid word when joined together.