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.
Code
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 earlythrowwhen 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
Caesar CipherShift letters by any integer amount to encode or decode Caesar ciphers, with case preservation and automatic round-trip verification.ROT13 EncoderApply the ROT13 letter rotation to any text: letters shift thirteen places, non-letters pass through, and the transform is self-inverse.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.