|
| 1 | +import {Trie, ObjectNode} from '@aureooms/js-trie'; |
| 2 | +import {push, iter} from '@aureooms/js-persistent-stack'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Simple Lempel-Ziv lossless data compression algorithm implementation. |
| 6 | + */ |
| 7 | + |
| 8 | +// TODO read input as async tape |
| 9 | +// TODO await trie operations |
| 10 | +// TODO use persistent trie |
| 11 | + |
| 12 | +export function* encode({trie, table}, symbols) { |
| 13 | + let chunkNumber = table.length - 1; |
| 14 | + const itSymbols = symbols[Symbol.iterator](); |
| 15 | + while (true) { |
| 16 | + const [part, node] = trie.getClosestAncestor(itSymbols); |
| 17 | + if (part === undefined) { |
| 18 | + yield [node.value(), undefined]; |
| 19 | + break; |
| 20 | + } |
| 21 | + |
| 22 | + node.set(part, ++chunkNumber); |
| 23 | + |
| 24 | + yield [node.value(), part]; |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +const reify = (chunk) => [...iter(chunk)].reverse().join(''); |
| 29 | + |
| 30 | +// TODO use persistent table |
| 31 | + |
| 32 | +export function* decode({table}, tokens) { |
| 33 | + for (const [parent, child] of tokens) { |
| 34 | + const previous = table[parent]; |
| 35 | + |
| 36 | + if (child === undefined) { |
| 37 | + yield reify(previous); |
| 38 | + } else { |
| 39 | + const newChunk = push(previous, child); |
| 40 | + yield reify(newChunk); |
| 41 | + table.push(newChunk); |
| 42 | + } |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +// TODO use persistent dict (hence a persistent trie and table) |
| 47 | +export const dict = (symbols = ['']) => { |
| 48 | + const trie = makeTrie(symbols); |
| 49 | + const table = makeTable(trie); |
| 50 | + return {trie, table}; |
| 51 | +}; |
| 52 | + |
| 53 | +const makeTable = (trie) => { |
| 54 | + const table = []; |
| 55 | + for (const [key, value] of trie) table[value] = key; |
| 56 | + return table; |
| 57 | +}; |
| 58 | + |
| 59 | +const emptyTrie = () => { |
| 60 | + const root = new ObjectNode(); |
| 61 | + const trie = new Trie(root); |
| 62 | + return trie; |
| 63 | +}; |
| 64 | + |
| 65 | +const makeTrie = (symbols) => { |
| 66 | + const trie = emptyTrie(); |
| 67 | + let i = 0; |
| 68 | + for (const x of symbols) trie.set(x, i++); |
| 69 | + return trie; |
| 70 | +}; |
0 commit comments