|
| 1 | +# Compact Prefix Tree |
| 2 | + |
| 3 | +A serializable compact prefix tree (also known as Radix tree or Patricia tree or space-optimized trie) implementation in JavaScript. |
| 4 | + |
| 5 | +## Usage |
| 6 | + |
| 7 | +### Installation |
| 8 | + |
| 9 | +``` bash |
| 10 | +npm install compact-prefix-tree |
| 11 | +``` |
| 12 | + |
| 13 | +### General Usage |
| 14 | + |
| 15 | +``` js |
| 16 | +const { CompactPrefixTree } = require("compact-prefix-tree"); |
| 17 | + |
| 18 | +const items = [ |
| 19 | + "http://www.example.com/foo/", |
| 20 | + "http://www.example.com/baz/", |
| 21 | +]; |
| 22 | + |
| 23 | +// create a trie from array of strings |
| 24 | +const trie = new CompactPrefixTree(items); |
| 25 | +// can add items later |
| 26 | +trie.add("http://www.example.com/john/"); |
| 27 | + |
| 28 | +// look for a prefix of a word |
| 29 | +const p1 = trie.prefix("http://www.example.com/john/doe"); |
| 30 | +// p1: { prefix: "http://www.example.com/john/", isProper: true } |
| 31 | +const p2 = trie.prefix("http://www.example.com/bazinga"); |
| 32 | +// p2: { prefix: "http://www.example.com/", isProper: false } |
| 33 | +// above is not proper as it doesn't exist in list of items provided |
| 34 | +``` |
| 35 | + |
| 36 | +### Serialization |
| 37 | + |
| 38 | +``` js |
| 39 | +const { CompactPrefixTree, getWordsFromTrie } = require("compact-prefix-tree"); |
| 40 | +const items = [ |
| 41 | + "http://www.example.com/foo/", |
| 42 | + "https://www.example.com/baz/", |
| 43 | +]; |
| 44 | +const trie = new CompactPrefixTree(items); |
| 45 | +const serialized = JSON.stringify(trie.T); |
| 46 | +// { |
| 47 | +// "http": { |
| 48 | +// "://www.example.com/foo/": null, |
| 49 | +// "s://www.example.com/baz/": null |
| 50 | +// } |
| 51 | +// } |
| 52 | + |
| 53 | +const words = getWordsFromTrie(JSON.parse(serialized)); |
| 54 | +// Set(2) {"http://www.example.com/foo/" "https://www.example.com/baz/"} |
| 55 | + |
| 56 | +const trie2 = new CompactPrefixTree(Array.from(words)); |
| 57 | +// assert(isEqual(trie.items, trie2.items)); |
| 58 | +``` |
| 59 | + |
| 60 | +## License |
| 61 | + |
| 62 | +[MIT License] Copyright 2018 Sid Vishnoi (https://sidvishnoi.github.io) |
0 commit comments