Compress a string with run-length encoding in JavaScript
Advanced · 4 min read
Run-length encoding is one of the simplest ways to make data smaller. Instead of writing aaa, you write 3a: the count, then the character. So 'aaabbc' becomes '3a2bc'. It works well on data with long runs of the same value, such as simple images with large areas of one color.
In this tutorial you will write encode, which leaves out the count for a single character so the output never grows. You will compare it with a version that always writes a count, and then find the input that breaks both of them. You should know while loops, string indexing and String(). A run is explained below.
What a run is
A run is a stretch of the same character repeated. 'aaabbc' has three runs: aaa, bb and c. Encoding means measuring each run, writing its length and its character, then jumping to the start of the next run.
The rule for a run of one
If you always write the count, c becomes 1c, and text with no repeats doubles in size. So this version writes a count only for runs of two or more. A single c stays c.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
57 Run-length encode
hardCompress 'aaabbc' to '3a2bc': a run of two or more gets a count, a single character does not. Then find the input that makes the output ambiguous.
Stuck? Three hints, smallest first
- 1. Walk the string, measure the run at each position, and jump past it.
- 2. Omitting the count for a run of one keeps the output from growing.
- 3. Ask what happens when the text itself contains digits.
Step 1: measure one run
const text = 'aaabbc';
let i = 0;
let run = 1;
while (text[i + run] === text[i]) run++;
console.log(run); // 3
Start at position i with a run of 1, the character itself. Keep looking one further along while the next character is the same. At text[3] we find b, so the run of a is 3.
When i + run goes past the end, text[i + run] is undefined, which never equals a character, so the loop always stops.
Step 2: write the run and jump past it
function encode(text) {
let out = '';
let i = 0;
while (i < text.length) {
let run = 1;
while (text[i + run] === text[i]) run++;
out += (run > 1 ? String(run) : '') + text[i];
i += run;
}
return out;
}
console.log(encode('aaabbc')); // '3a2bc'
console.log(encode('abc')); // 'abc'
console.log(encode('aa')); // '2a'
After writing a run, i += run jumps straight to the next new character, so no character is counted twice. run > 1 ? String(run) : '' leaves the count out for single characters.
Step 3: edge cases
function encode(text) {
let out = '';
let i = 0;
while (i < text.length) {
let run = 1;
while (text[i + run] === text[i]) run++;
out += (run > 1 ? String(run) : '') + text[i];
i += run;
}
return out;
}
console.log(JSON.stringify(encode(''))); // ""
console.log(encode('a'.repeat(12))); // '12a'
An empty string never enters the loop. A run longer than nine gets a two-digit count, 12a. Whoever reads the encoded text back has to know that a count can have more than one digit.
Step 4: the always-count version
The other design writes a count every time. A regex can do it in one line:
const encodeStrict = (text) => text.replace(/(.)\1*/gs, (run, c) => String(run.length) + c);
console.log(encodeStrict('aaabbc')); // '3a2b1c'
console.log(encodeStrict('abc')); // '1a1b1c'
(.) captures one character. \1* means "the same character again, zero or more times", so the whole match is one run. The s flag lets . match newlines too. The callback gets the whole run and its character, and returns the length plus the character.
It is simple and regular, but on text with no repeats the output is twice as long as the input. The compact encode from Step 2 never gets longer.
Step 5: the input that breaks it
What if the text itself contains digits?
function encode(text) {
let out = '';
let i = 0;
while (i < text.length) {
let run = 1;
while (text[i + run] === text[i]) run++;
out += (run > 1 ? String(run) : '') + text[i];
i += run;
}
return out;
}
const encodeStrict = (text) => text.replace(/(.)\1*/gs, (run, c) => String(run.length) + c);
console.log(encode('a3')); // 'a3'
console.log(encodeStrict('a3')); // '1a13'
encode('a3') gives a3. Is that the letter a and the digit 3, or the start of "three of something"? A decoder can't tell. encodeStrict('a3') gives 1a13. Here a decoder that reads all the digits it can takes 13 as a count, and there is no character left for it to repeat.
Neither output can be decoded back reliably. Run-length encoding only works when the text has no digits in it, or when the format uses a special escape character to mark where a count begins.
The full solution
The panel has both encoders and prints 'aaabbc', 'abc' both ways, and the ambiguous 'a3'. Press Run, then read the checks underneath.
function encode(text) {
let out = '';
let i = 0;
while (i < text.length) {
let run = 1;
while (text[i + run] === text[i]) run++;
out += (run > 1 ? String(run) : '') + text[i]; // no count for a run of one
i += run;
}
return out;
}
// The always-count variant. Simpler, unambiguous about where a count starts,
// and able to make the output longer than the input.
const encodeStrict = (text) => text.replace(/(.)\1*/gs, (run, c) => String(run.length) + c);
console.log("encode('aaabbc') :", encode('aaabbc'));
console.log("encode('abc') :", encode('abc'));
console.log("encodeStrict('abc') :", encodeStrict('abc'), '<- longer than the input');
console.log("encode('a3') :", encode('a3'), '<- is that a run, or the text "a3"?');
Output
12 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 12 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a run of three collapses', encode('aaabbc'), '3a2bc');
test('a single character carries no count', encode('abc'), 'abc');
test('an empty string encodes to nothing', encode(''), '');
test('a run of two', encode('aa'), '2a');
test('a run longer than nine uses two digits', encode('a'.repeat(12)), '12a');
test('the always-count variant writes a count every time', encodeStrict('aaabbc'), '3a2b1c');
test('which makes it longer than the input on text with no runs', encodeStrict('abc'), '1a1b1c');
test('measurably longer', encodeStrict('abc').length > 'abc'.length, true);
test('while the compact version never grows', encode('abc').length <= 'abc'.length, true);
test('but the compact output is AMBIGUOUS when the text has digits', encode('a3'), 'a3');
test('and the strict form does not rescue it either', encodeStrict('a3'), '1a13');
test('so run-length encoding needs an alphabet with no digits in it', /[0-9]/.test('aaabbc'), false);
Run-length encoding is only a compression scheme if the alphabet excludes the count characters. encode('a3') produces 'a3', which is exactly what a run of three would look like without its letter, and encodeStrict('a3') produces '1a13', where a greedy digit reader takes 13 as the count and runs off the end. Neither is recoverable, which is why real formats reserve an escape byte.
The two variants trade different things. Omitting the count for a run of one guarantees the output never grows, at the cost of the ambiguity above. Always writing it makes parsing trivial and makes worst-case output twice the input.
Common mistakes
- Moving forward one character at a time. Each run gets counted again from its second character. Jump with
i += run. - Assuming counts are one digit. Twelve
as encode as12a. Anything reading the output must handle that. - Encoding text that contains digits. The result is ambiguous. Check the input first, or use an escape character.
Try it yourself
- Write
isSafeToEncode(text)that returnsfalseif the text contains any digit. - Change
encodeto write runs asa3(character first, then count) and check whether that removes the ambiguity. - Compare
encode(text).lengthwithtext.lengthfor a few inputs and find one that shrinks by more than half.