mramine364

lz78 compression

Jun 26th, 2016
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function lz78_encode(str){
  2.     let d=[], s="", ind=-1, i, j, dcom=[];
  3.     for(i=0; i<str.length; i++){
  4.         s+=str[i];
  5.         for(j=0; j<d.length; j++){
  6.             if( s==dcom[j] ){
  7.                 ind=j;
  8.                 break;
  9.             }
  10.         }
  11.         if( j==d.length ){
  12.             d.push({index: ind+1, char: str[i]});
  13.             dcom.push(((ind==-1)?"":dcom[ind])+str[i]);
  14.             s="";
  15.             ind=-1;
  16.         }else if( i+1==str.length ){
  17.             d.push({index: ind+1, char: ""});
  18.         }
  19.     }
  20.     return d;
  21. }
  22.  
  23. function lz78_decode(d){
  24.     let res="", str=[];
  25.     for(let i=0; i<d.length; i++){
  26.         if( d[i].index==0 ){
  27.             res+=d[i].char;
  28.             str.push(d[i].char);
  29.         }else{
  30.             res+=str[d[i].index-1]+d[i].char;
  31.             str.push(str[d[i].index-1]+d[i].char);
  32.         }
  33.     }
  34.     return res;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment