-
Notifications
You must be signed in to change notification settings - Fork 236
/
Copy pathcompress.js
46 lines (37 loc) · 983 Bytes
/
compress.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
// 1.5) Implement Basic string compression using # of repeated chars.
// If compressed string is longer than original, use original.
function compress(toCompress) {
const result = [];
let current = '^';
let numSame = 0;
let index = -1; // index of entry in result
function writeNum() {
const count = numSame.toString();
const countSize = count.length;
if ((index + countSize + 1) > toCompress.length) {
return false;
}
for (let i = 0; i < countSize; i++) {
result[index + i] = count[i];
}
return true;
}
for (let j = 0; j < toCompress.length; j++) {
const letter = toCompress[j];
if (letter !== current) {
index += numSame.toString().length;
// reset numSame
numSame = 1;
result[index] = letter;
index++;
current = letter;
} else {
numSame++;
}
if (!writeNum()) {
return toCompress;
}
}
return result.join('');
}
module.exports = compress;