Run-Length Encoding For Strings

Encode repeated characters into compact count-letter runs and decode them back with strict validation of malformed input.

JavascriptData Integrity

Code

javascriptsnippet
32 lines
export function runLengthEncode(input) {
  if (typeof input !== "string") throw new TypeError("input must be a string");
  const characters = [...input];
  let encoded = "";
  for (let index = 0; index < characters.length; ) {
    let run = 1;
    while (index + run < characters.length && characters[index + run] === characters[index]) {
      run += 1;
    }
    encoded += run + characters[index];
    index += run;
  }
  return encoded;
}

export function runLengthDecode(encoded) {
  if (typeof encoded !== "string") throw new TypeError("encoded must be a string");
  const token = /(\d+)([\s\S])/gu;
  let decoded = "";
  let consumed = 0;
  for (const match of encoded.matchAll(token)) {
    if (match.index !== consumed) throw new SyntaxError("invalid run-length token");
    const count = Number(match[1]);
    if (!Number.isSafeInteger(count) || count <= 0) {
      throw new RangeError("run length must be a positive safe integer");
    }
    decoded += match[2].repeat(count);
    consumed = match.index + match[0].length;
  }
  if (consumed !== encoded.length) throw new SyntaxError("invalid run-length token");
  return decoded;
}

Inside the snippet

Count the functions runLengthEncode and runLengthDecode as the entire surface area of Run-Length Encoding For Strings.

Iteration is nested: for (let index = 0; index < characters.length; ) frames the pass, while (index + run < characters.length && characters[index + run] === characters[index]) does the per-item step. Failure is loud: TypeError, SyntaxError and RangeError aborts the current operation instead of degrading it.

What to watch for

  • The guard typeof input !== "string" short-circuits the flow with an early throw when its condition holds.

Putting it to use

The main signature reads export function runLengthEncode(input)

The surface worth importing is runLengthEncode; the helpers around it are private to the snippet.

Core lines

if (consumed !== encoded.length) throw new SyntaxError("invalid run-length token");
if (typeof encoded !== "string") throw new TypeError("encoded must be a string");
if (match.index !== consumed) throw new SyntaxError("invalid run-length token");

Interactive Tools for This Topic

FAQ

How does the code behave when input is bad?
The code throws `TypeError`, `SyntaxError` and `RangeError` — the guard `typeof input !== "string"` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. The file defines `runLengthEncode`, `runLengthDecode` at load time.