UNPKG

huffman-ts

Version:

Huffman ts is an implementation of Huffman Algorithm in Typescript. It provides full compatibility with Huffman algorithm reference.

3 lines (2 loc) 2.71 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=function(){function e(){this.left=null,this.right=null,this.value=null}var t=e.prototype;return t.isLeaf=function(){return null===this.left&&null===this.right},t.encode=function(){return this.value?this.value:[this.left.encode(),this.right.encode()]},e}(),t=function(){function t(t){this.leafCache={},this.root=t||new e}var r=t.prototype;return r.stringToBitString=function(e){if(!e)return"";var t=e.split(""),r=parseInt(t.pop()),n="";return(n=t.map((function(e){return void 0===(t=e.charCodeAt(0).toString(2))&&(t=""),void 0===r&&(r=8),"0".repeat(r-t.length)+t;var t,r})).join("")).substr(0,n.length-r)},r.bitStringToString=function(e){var t=8-e.length%8,r="";e+="0".repeat(t);for(var n=0;n<e.length;n+=8)r+=String.fromCharCode(parseInt(e.substr(n,8),2));return r+t.toString()},r.encode=function(e){var t=this.encodeBitString(e);return this.bitStringToString(t)},r.decode=function(e){var t=this;if(!e)return"";var r="",n=this.stringToBitString(e),i=this.root;return n.split("").forEach((function(e){(i=i["0"===e?"left":"right"]).isLeaf()&&(r+=i.value,i=t.root)})),r},r.encodeBitString=function(e){var t=this;return e.split("").map((function(e){return t.bitValue(e)})).join("")},r.bitValue=function(e){return this.leafCache[e]||this.generateLeafCache(),this.leafCache[e]},r.generateLeafCache=function(e,t){void 0===e&&(e=this.root),void 0===t&&(t=""),e.isLeaf()?this.leafCache[e.value]=t:(this.generateLeafCache(e.left,t+"0"),this.generateLeafCache(e.right,t+"1"))},r.encodeTree=function(){return this.root.encode()},t.decodeTree=function(e){return new t(t.parseNode(e))},t.parseNode=function(r){var n=new e;return Array.isArray(r)?(n.left=t.parseNode(r[0]),n.right=t.parseNode(r[1])):n.value=r,n},t}(),r=function(){function e(e){this.rawString=e}var r=e.prototype;return r.build=function(){var e=this.buildFrequencyTable(),r=this.combineTable(e),n=this.compressCombinedTable(r);return t.decodeTree(n)},r.frequencySorter=function(e,t){return e[1]-t[1]},r.combineTable=function(e){for(;e.length>1;){var t=e.shift(),r=e.shift();e.unshift([[t,r],t[1]+r[1]]),e.sort(this.frequencySorter)}return e[0]},r.buildFrequencyTable=function(){var e={};return this.rawString.split("").forEach((function(t){e[t]=e[t]?e[t]+1:1})),Object.entries(e).sort(this.frequencySorter)},r.compressCombinedTable=function(e){var t=e[0];return Array.isArray(t)?[this.compressCombinedTable(t[0]),this.compressCombinedTable(t[1])]:t},e}();exports.Huffman=function(){function e(){}return e.treeFromText=function(e){return new r(e).build()},e.decodeTree=function(e){return t.decodeTree(e)},e}(),exports.Tree=t; //# sourceMappingURL=huffman-ts.cjs.production.min.js.map