Skip to content

There and back again

All labs

Encoding and decoding are the easiest place to see what a property buys you. The rule — decode of encode is the original — is one line, holds for every input, and is far stronger than any three examples you would think to write.

goalPin the round trip, the idempotence and the empty case with properties.

The module

export function encode(values) {
  return values.map((value) => String(value).length + ":" + value).join("");
}

export function decode(text) {
  const out = [];
  let index = 0;
  while (index < text.length) {
    const colon = text.indexOf(":", index);
    if (colon === -1) {
      break;
    }
    const length = Number(text.slice(index, colon));
    out.push(text.slice(colon + 1, colon + 1 + length));
    index = colon + 1 + length;
  }
  return out;
}

Your tests

Mutants

Run the suite to see the board.