-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrie.ts
66 lines (62 loc) · 1.74 KB
/
trie.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { Unpacker } from "../binary-utils/Unpacker";
import { NodeType, Node, Leaf } from "../types";
export function extractBytes(
unpacker,
tree,
dataLength,
maxBitsLength,
minBitsLength
) {
let outputBytes: number[] = [];
for (let i = 0; i < dataLength; i++) {
const byte = findNextByte(tree, unpacker, maxBitsLength, minBitsLength);
outputBytes.push(byte);
}
return outputBytes;
}
export function findNextByte(
tree: NodeType,
unpacker: Unpacker,
maxBitsLength: number,
minBitsLength: number
) {
let nextByteLengthInBits = minBitsLength;
while (nextByteLengthInBits <= maxBitsLength) {
const possibleNextByte = Array.from(
unpacker.peek(nextByteLengthInBits)
) as number[];
const isNextByteInTree = trieSearch(tree, possibleNextByte);
if (isNextByteInTree.found === true) {
unpacker.dropBits(nextByteLengthInBits);
nextByteLengthInBits = minBitsLength;
return isNextByteInTree.byte;
} else {
nextByteLengthInBits++;
}
}
throw new Error(`No matching byte found`);
}
function trieSearch(tree: NodeType, possibleNextByte: number[]) {
let cloneTree = tree;
for (let i = 0; i < possibleNextByte.length; i++) {
const nextBit = possibleNextByte[i];
if (nextBit === 0) {
if (cloneTree instanceof Node) {
cloneTree = cloneTree.left;
} else {
return { found: false as const, byte: null };
}
} else {
if (cloneTree instanceof Node) {
cloneTree = cloneTree.right;
} else {
return { found: false as const, byte: null };
}
}
}
if (cloneTree && cloneTree instanceof Leaf) {
return { found: true as const, byte: cloneTree.byte };
} else {
return { found: false as const, byte: null };
}
}