Run-length encoding in JavaScript
Intermediate · 4 min read
Run-length encoding (RLE) is one of the simplest ways to make data smaller. Instead of storing aaaaa, you store a5: the character and how many times it repeats. A run of the same character is called a run, hence the name. Simple images, fax machines and sensor logs that hold the same value for a long time all use ideas like this.
In this tutorial you will write encode, which squashes runs, and decode, which expands them again. Then you'll find two limits: text that RLE makes longer, and text it can't get back at all. You need to know while loops and string indexes. Everything else is explained as we go.
What the format looks like
Each run becomes the character followed by its count:
aaabbc -> a3b2c1
lllaaagggooosss -> l3a3g3o3s3
To decode, read a character, read the number after it, and repeat the character that many times. repeat does the repeating:
console.log('a'.repeat(3)); // aaa
console.log('b'.repeat(0)); // (an empty string)
Here is the exercise. Try it on your own first if you like, or read on and we will build it together.
141 Squash repeats with run-length encoding
fairCompress a string by replacing each run of identical characters with the character and how many times it repeated, then write the decoder. Show a string the format makes longer, and a string it cannot survive a round trip.
Stuck? Three hints, smallest first
- 1. Walk forward, counting how far the current character continues.
- 2. Decoding, a run length can be more than one digit, so read digits until they stop.
- 3. Ask what happens when the text being encoded already contains digits.
Step 1: measure one run
Start at position i and count how far the same character continues:
const text = 'aaabbc';
const i = 0;
let run = 1;
while (i + run < text.length && text[i + run] === text[i]) run++;
console.log(run); // 3
run starts at 1, because the character at i is itself part of the run. The loop looks one further each time and stops at the first different character, or the end of the text. The i + run < text.length check comes first so we never read past the end.
Step 2: the encoder
Now wrap that in an outer loop. After measuring a run, write it out and jump past it by adding run to i:
function encode(text) {
let out = '';
let i = 0;
while (i < text.length) {
let run = 1;
while (i + run < text.length && text[i + run] === text[i]) run++;
out += text[i] + run;
i += run;
}
return out;
}
console.log(encode('aaabbc')); // a3b2c1
console.log(encode('lllaaagggooosss')); // l3a3g3o3s3
console.log(encode('a'.repeat(12))); // a12
console.log(encode('')); // (an empty string)
Because i jumps over each run, every character is looked at only once. text[i] + run joins a string and a number, so JavaScript turns the number into text: 'a' + 3 is 'a3'.
Step 3: the decoder, first try
The obvious decoder reads two characters at a time, a letter and a count:
function decodePairs(text) {
let out = '';
for (let i = 0; i < text.length; i += 2) {
out += text[i].repeat(Number(text[i + 1]));
}
return out;
}
console.log(decodePairs('a3b2c1')); // aaabbc
console.log(decodePairs('a12').length); // 1
It works for a3b2c1. But a run of 12 is written a12, with a two-digit count. Reading one digit gives a single a, and then the 2 is read as a character, with no count after it. Number(undefined) is NaN, and repeating NaN times gives nothing. We get one a instead of twelve.
Step 4: read digits until they stop
The fix is to keep reading while the next character is a digit:
function decode(text) {
let out = '';
let i = 0;
while (i < text.length) {
const ch = text[i];
let j = i + 1;
while (j < text.length && text[j] >= '0' && text[j] <= '9') j++; // multi-digit runs
out += ch.repeat(Number(text.slice(i + 1, j)));
i = j;
}
return out;
}
console.log(decode('a3b2c1')); // aaabbc
console.log(decode('a12').length); // 12
console.log(decode('l3a3g3o3s3')); // lllaaagggooosss
j starts just after the character and moves forward over every digit. text.slice(i + 1, j) is the whole count, like '12'. Then i = j jumps to the next character.
Step 5: the two limits
RLE only helps when there are runs. Text without repeats gets twice as long:
function encode(text) {
let out = '';
let i = 0;
while (i < text.length) {
let run = 1;
while (i + run < text.length && text[i + run] === text[i]) run++;
out += text[i] + run;
i += run;
}
return out;
}
function decode(text) {
let out = '';
let i = 0;
while (i < text.length) {
const ch = text[i];
let j = i + 1;
while (j < text.length && text[j] >= '0' && text[j] <= '9') j++;
out += ch.repeat(Number(text.slice(i + 1, j)));
i = j;
}
return out;
}
console.log(encode('abc')); // a1b1c1
console.log(encode('Lagos')); // L1a1g1o1s1
console.log(encode('a1')); // a111
console.log(decode(encode('a1')).length); // 111
The worse problem is the last two lines. The text a1 contains a digit. It encodes to a111: "a once, then 1 once". But the decoder can't tell the digit in the text from a count, so it reads "a, 111 times". Nothing throws an error. You just get the wrong answer, quietly.
A format that can hold any text needs a way to mark which digits are counts, for example a special escape character. For text that never contains digits, this simple version is fine. Just say so wherever it's used.
The full solution
The answer panel has encode and decode, round-trips a repetitive string, and prints what happens to a1. The checks also cover a 12-long run, the empty string, and text that grows. Press Run to see the output.
function encode(text) {
let out = '';
let i = 0;
while (i < text.length) {
let run = 1;
while (i + run < text.length && text[i + run] === text[i]) run++;
out += text[i] + run;
i += run;
}
return out;
}
function decode(text) {
let out = '';
let i = 0;
while (i < text.length) {
const ch = text[i];
let j = i + 1;
while (j < text.length && text[j] >= '0' && text[j] <= '9') j++; // multi-digit runs
out += ch.repeat(Number(text.slice(i + 1, j)));
i = j;
}
return out;
}
const chant = 'lllaaagggooosss';
console.log(chant, '->', encode(chant));
console.log('and back ->', decode(encode(chant)));
console.log('but encode("a1") is', encode('a1'), 'which decodes to', decode(encode('a1')).length, 'characters');
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('runs collapse', encode('aaabbc'), 'a3b2c1');
test('and come back', decode('a3b2c1'), 'aaabbc');
test('a full round trip on a repetitive string', decode(encode(chant)), chant);
test('a run longer than nine digits stays one run', [encode('a'.repeat(12)), decode('a12').length], ['a12', 12]);
test('nothing in, nothing out', [encode(''), decode('')], ['', '']);
test('with no repeats at all it doubles the length', [encode('abc'), encode('abc').length], ['a1b1c1', 6]);
test('so it only pays on runs, and this text has none worth having', encode('Lagos').length > 'Lagos'.length, true);
test('a digit in the input breaks the round trip badly', [encode('a1'), decode(encode('a1')).length], ['a111', 111]);
test('and the damage is silent: nothing throws, the answer is just wrong', decode(encode('a1')) === 'a1', false);
The encoder is two nested walks with one pointer, which is the shape worth learning: the inner loop measures the run, the outer loop jumps past it, so every character is looked at once. The decoder needs the digit loop because a run of 12 is two characters — reading a single character as the count is the bug that makes a12 decode to one a followed by a stray 2.
The last two assertions are the real lesson, and it is about formats rather than loops. This encoding has no way to tell a literal digit in the input from a count, so 'a1' encodes to 'a111' and decodes to 111 copies of a. Nothing throws. The output is a plausible string of the wrong length, which is how corruption spreads. A format that can express any input needs an escape character, or a length prefix, or a restricted alphabet stated up front.
And compression is not free. Run-length encoding doubles the size of text with no repeats, which is most text — it earns its keep on scanned black-and-white images, simple bitmaps and sensor readings that hold steady, not on prose. Measuring before and after, as the sixth assertion does, is the habit.
Common mistakes
- Reading a single digit as the count. Runs of 10 or more have longer counts. Read digits until they stop.
- Moving
iforward by one instead of by the run. Each run gets encoded again from its second character. - Assuming the text has no digits. The round trip breaks silently. Check the input or use an escape character.
Try it yourself
- Leave out the count when it's 1, so
aaabcbecomesa3bc. Update the decoder to match. - Write
ratio(text)that returnsencode(text).length / text.length, and try it on a few strings. - Make
encodethrow an error when the text contains a digit, so the bad round trip can't happen.