Advertisement
Mangus875

JavaScript text compression [WIP]

Oct 31st, 2023 (edited)
910
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const numToBin = num => num.toString(2);
  2. const binToNum = bin => parseInt(bin,2);
  3.  
  4. function buildTree(freqs) {
  5.     let tree = [];
  6.     let sorted = [];
  7.     let check = 1;
  8.     // sort chars by frequency
  9.     while (sorted.length != Object.keys(freqs).length) {
  10.         for (const i in freqs) {
  11.             if (freqs[i] == check) {
  12.                 sorted.push(i);
  13.             }
  14.         }
  15.         check++;
  16.     }
  17.     // sorted.reverse();
  18.     tree = sorted.map((v) => {
  19.         return [v, freqs[v]]
  20.     });
  21.     // console.log(sorted);
  22.    
  23.     // create tree
  24.     while (tree.length > 1) {
  25.         let newElem = [[tree[0][0],tree[1][0]], tree[0][1]+tree[1][1]];
  26.        
  27.         tree = tree.slice(2);
  28.         let slot = 0;
  29.         while (slot < tree.length && tree[slot+1][1] <= newElem[1]) {
  30.             slot++;
  31.         }
  32.         tree.splice(slot+1, 0, newElem);
  33.     }
  34.    
  35.     let newTree = [];
  36.    
  37.     return tree;
  38. }
  39.  
  40. function assignKeys(tree) {
  41.     let keys = [];
  42. }
  43.  
  44. function compressText(txt) {
  45.     let chars = [];
  46.     let freqs = [];
  47.     for (let i = 0; i < txt.length; i++) {
  48.         let code = txt[i].charCodeAt(0);
  49.        
  50.         if (freqs[txt[i]] == undefined) {
  51.             freqs[txt[i]] = 1;
  52.         } else {
  53.             freqs[txt[i]]++;
  54.         }
  55.        
  56.         chars.push(code);
  57.     }
  58.    
  59.     console.log(buildTree(freqs));
  60. }
  61. compressText("The FitnessGram Pacer Test is a multistage aerobic capacity test that progressively gets more difficult as it continues. The 20 meter pacer test will begin in 30 seconds. Line up at the start. The running speed starts slowly, but gets faster each minute after you hear this signal. [beep] A single lap should be completed each time you hear this sound. [ding] Remember to run in a straight line, and run as long as possible. The second time you fail to complete a lap before the sound, your test is over. The test will begin on the word start. On your mark, get ready, start.");
  62.  
  63. function decompressText(data) {}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement