How to compress a string in JavaScript

Here is one way to compress a string in JavaScript.
Space complexity: O(n) for storing a compressed version of the string
Time complexity: O(n). We must iterate through the entire string at least once.

compressStringTry in REPL
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
function compress(string) {
if (typeof string !== 'string') return null;
if (string === '') return '';
let trackingChar = string[0];
let charCount = 0;
let compressed = '';
for (let i = 0; i < string.length; i++) {
const char = string[i];
if (char === trackingChar) {
charCount++;
} else if (char !== trackingChar) {
compressed += trackingChar + (charCount === 1 ? '' : '' + charCount);
trackingChar = char;
charCount = 1;
}
}
compressed += trackingChar + (charCount === 1 ? '' : '' + charCount);
return compressed.length < string.length ? compressed : string;
}
// ==== Tests
function runTests(func) {
const inputOutput = [[null, null], ['', ''], ['AABBCC', 'AABBCC'], ['AAABCCDDDD', 'A3BC2D4'], ['BAAACCDDDD', 'BA3C2D4'], ['AAABAACCDDDD', 'A3BA2C2D4']];
for (let i = 0; i < inputOutput.length; i++) {
const input = inputOutput[i].slice(0, inputOutput[i].length-1);
const expected = inputOutput[i][inputOutput[i].length-1];
const result = func(...input);
if (result !== expected) {
return `Test failed: Expected - ${expected}. Got ${result}`;
}
}
return 'All tests passed!'
}
runTests(compress); // All tests passed
// Test cases
// compress(null); // null
// compress(''); // ''
// compress('AABBCC') // 'AABBCC'
// compress('AAABCCDDDD') // 'A3BC2D4'
// compress('BAAACCDDDD') // 'BA3C2D4'
// compress('AAABAACCDDDD') // 'A3BA2C2D4'