Caesar Cipher and ROT13 Text Shifting

Shift ASCII letters by any integer offset with alphabet wrapping, and expose ROT13 as a fixed thirteen-position special case.

JavascriptSecurity Boundaries

Code

javascriptsnippet
17 lines
function shiftLetters(text, offset) {
  if (typeof text !== "string") throw new TypeError("text must be a string");
  if (!Number.isInteger(offset)) throw new TypeError("offset must be an integer");
  const normalized = ((offset % 26) + 26) % 26;
  return text.replace(/[a-z]/gi, (char) => {
    const base = char <= "Z" ? 65 : 97;
    return String.fromCharCode(((char.charCodeAt(0) - base + normalized) % 26) + base);
  });
}

export function caesarCipher(text, offset) {
  return shiftLetters(text, offset);
}

export function rot13(text) {
  return shiftLetters(text, 13);
}

What the code does

The working surface is the functions normalized, shiftLetters, caesarCipher and rot13 — everything else is wiring.

A guard precedes the TypeError: bad state stops the flow there instead of continuing.

Points of care

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

Applying it

The primary signature is export function caesarCipher(text, offset)

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

Statements that matter

return text.replace(/[a-z]/gi, (char) => {
const base = char <= "Z" ? 65 : 97;
return String.fromCharCode(((char.charCodeAt(0) - base + normalized) % 26) + base);
});
if (!Number.isInteger(offset)) throw new TypeError("offset must be an integer");
if (typeof text !== "string") throw new TypeError("text must be a string");

Interactive Tools for This Topic

FAQ

What happens if the preconditions do not hold?
The code throws `TypeError` — the guard `typeof text !== "string"` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `normalized`, `shiftLetters`, `caesarCipher` at load time.