-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrle.js
More file actions
84 lines (70 loc) · 2.66 KB
/
rle.js
File metadata and controls
84 lines (70 loc) · 2.66 KB
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
83
84
function compressString(inputString) {
const length = inputString.length;
let differentCount = 0;
let equalCount = 0;
let result = [];
let tempStr = "";
for (let i = 0; i < length; i++) {
const currentChar = inputString[i];
const nextChar = inputString[i + 1];
const prevChar = inputString[i - 1];
if (currentChar !== nextChar && currentChar !== prevChar) {
differentCount++;
tempStr += currentChar;
if (equalCount > 0) {
result.push(String.fromCharCode(equalCount + 128) + prevChar);
equalCount = 0;
}
if (differentCount === 127) {
result.push(String.fromCharCode(differentCount) + tempStr);
tempStr = "";
differentCount = 0;
}
} else {
equalCount++;
if (differentCount > 0) {
result.push(String.fromCharCode(differentCount) + tempStr);
tempStr = "";
differentCount = 0;
}
if (equalCount === 127 || currentChar !== nextChar) {
result.push(String.fromCharCode(equalCount + 128) + currentChar);
equalCount = 0;
}
}
}
if (differentCount > 0) {
result.push(String.fromCharCode(differentCount) + tempStr);
}
if (equalCount > 0) {
result.push(String.fromCharCode(equalCount + 128) + inputString[length - 1]);
}
return result.join('');
}
function decompressString(compressedString) {
const length = compressedString.length;
const characters = compressedString.split('');
let result = [];
for (let i = 0; i < length; i++) {
const charCode = characters[i].charCodeAt(0);
if (charCode <= 127) {
let count = charCode + i;
for (; i < count; i++) {
result.push(characters[i + 1]);
}
} else {
let count = charCode - 128;
i++;
for (let j = 0; j < count; j++) {
result.push(characters[i]);
}
}
}
return result.join('');
}
const text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabcd";
const compressedText = compressString(text);
console.log("Original Text:\n", text);
console.log("Compressed Text:\n", compressedText);
const decompressedText = decompressString(compressedText);
console.log("Decompressed Text\n:", decompressedText);