()
| 68 | } |
| 69 | |
| 70 | public buildTree() { |
| 71 | const numSymbols = this.freqs.length; |
| 72 | |
| 73 | /* heap is a priority queue, sorted by frequency, least frequent |
| 74 | * nodes first. The heap is a binary tree, with the property, that |
| 75 | * the parent node is smaller than both child nodes. This assures |
| 76 | * that the smallest node is the first parent. |
| 77 | * |
| 78 | * The binary tree is encoded in an array: 0 is root node and |
| 79 | * the nodes 2*n+1, 2*n+2 are the child nodes of node n. |
| 80 | */ |
| 81 | const heap = new Int32Array(numSymbols); |
| 82 | let heapLen = 0; |
| 83 | let maxCode = 0; |
| 84 | for (let n = 0; n < numSymbols; n++) { |
| 85 | const freq = this.freqs[n]; |
| 86 | if (freq !== 0) { |
| 87 | // Insert n into heap |
| 88 | let pos = heapLen++; |
| 89 | while (true) { |
| 90 | if (pos > 0) { |
| 91 | const ppos = Math.floor((pos - 1) / 2); |
| 92 | if (this.freqs[heap[ppos]] > freq) { |
| 93 | heap[pos] = heap[ppos]; |
| 94 | pos = ppos; |
| 95 | } else { |
| 96 | break; |
| 97 | } |
| 98 | } else { |
| 99 | break; |
| 100 | } |
| 101 | } |
| 102 | heap[pos] = n; |
| 103 | |
| 104 | maxCode = n; |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | /* We could encode a single literal with 0 bits but then we |
| 109 | * don't see the literals. Therefore we force at least two |
| 110 | * literals to avoid this case. We don't care about order in |
| 111 | * this case, both literals get a 1 bit code. |
| 112 | */ |
| 113 | while (heapLen < 2) { |
| 114 | const node = maxCode < 2 ? ++maxCode : 0; |
| 115 | heap[heapLen++] = node; |
| 116 | } |
| 117 | |
| 118 | this.numCodes = Math.max(maxCode + 1, this.minNumCodes); |
| 119 | |
| 120 | const numLeafs = heapLen; |
| 121 | const childs = new Int32Array(4 * heapLen - 2); |
| 122 | const values = new Int32Array(2 * heapLen - 1); |
| 123 | let numNodes = numLeafs; |
| 124 | for (let i = 0; i < heapLen; i++) { |
| 125 | const node = heap[i]; |
| 126 | childs[2 * i] = node; |
| 127 | childs[2 * i + 1] = -1; |
no test coverage detected