-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (71 loc) · 1.95 KB
/
index.js
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
module.exports ={
encode(arr){
// escape char is 280
// format is (280 + escaped char [+ ...reference]) for each dictionary entry
const finalArr =[];
const dict = {};
let ind = 0;
let cur = '';
for(let i=0; i<arr.length; i++){
const char = arr[i];
const temp = cur + char;
const ref = dict[cur]? dict[cur].ind : null;
const isEnd = i === arr.length-1;
if(!dict[temp] || isEnd){
dict[temp] = {ind, ref};
// fill array
finalArr.push(280);
finalArr.push(char.charCodeAt(0)); // added char
if(ref !== null){
[...ref.toString()].forEach(digit=>{ // reference nums
finalArr.push(digit.charCodeAt(0));
});
}
ind++;
cur = '';
}else{
cur = temp;
}
}
finalArr.push(281);
console.log(`Modified lz78 compression: ${arr.length} bytes to ${finalArr.length} bytes`);
return finalArr;
},
decode(someArr){
const arr = someArr.map(val=>parseInt(val,10)); // convert to nums;
const pairs = [];
let decoded = '';
let ind = 0;
let ref = '';
let nextIsChar = true;
let endChar;
let hitEnd = false;
for(let i=1; i<arr.length;i++){
let num = arr[i];
switch(num){
case 281: // end of file
hitEnd = true;
case 280: // escape char. enter previous char,ref into dictionary and decode
const temp = ref? pairs[parseInt(ref,10)] + endChar: endChar;
pairs.push(temp);
decoded += temp;
ind++;
nextIsChar = true;
ref = '';
break;
default:
if(nextIsChar){
endChar = String.fromCharCode(num);
nextIsChar = false;
}else{
ref += String.fromCharCode(num);
}
}
if(hitEnd){
break;
}
}
console.log(`Modified lz78 decompression: ${arr.length} bytes to ${decoded.length} bytes`);
return decoded;
}
}