Caesar Cipher CLI
A Node CLI that shifts letters by a configurable key for encode or decode, preserving case and non-letters, with round-trip tests.
Project
node-caesar-cipher-cli
Entry point: caesar.mjs
Install
node --versionRun
node caesar.mjs encode 3 "Attack at dawn!"Test
node --test caesar.test.mjsExpected output
Prints the shifted text, for example Dwwdfn dw gdzq! for a shift of 3 applied to Attack at dawn!.Dependencies
- node >=20
What it does
Rotates letters within A-Z and a-z by the given shift and leaves every other character as-is. Decoding applies the inverse shift, so encode followed by decode returns the original text.
const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
export function shift(text, key) {
const k = ((key % 26) + 26) % 26;
return [...text].map((ch) => {
const lower = ch.toLowerCase();
const idx = ALPHA.indexOf(lower);
if (idx === -1) return ch;
const out = ALPHA[(idx + k) % 26];
return ch === lower ? out : out.toUpperCase();
}).join('');
}
const [mode, keyArg, ...rest] = process.argv.slice(2);
const key = Number(keyArg);
if (!Number.isInteger(key)) { console.error('usage: caesar <encode|decode> <key> <text>'); process.exit(1); }
const text = rest.join(' ');
console.log(shift(text, mode === 'decode' ? -key : key));
Run and verify
node caesar.mjs encode 3 "Attack at dawn!"
Run the test command to check the implementation: node --test caesar.test.mjs.
Expected Output
Each letter moves three positions forward; case is preserved and punctuation is untouched:
Dwwdfn dw gdzq!
Limitations
The Caesar cipher provides no security; it is a teaching tool and is trivially broken by brute force over the 26 possible keys.