Challenge: Secret notes with a Caesar cipher
Tariro and Kuda pass notes in class, and they do not want anyone else to read them. They use one of the oldest tricks in the book, the Caesar cipher: every letter moves a fixed number of places along the alphabet.
With a shift of 3:
a b c d e f g h i j k l m n o p q r s t u v w x y z
d e f g h i j k l m n o p q r s t u v w x y z a b c
So hello becomes khoor. To read the note, Kuda shifts the other way, by -3.
Your task
Write caesar(text, shift). It returns the text with every letter moved shift places along the alphabet.
caesar("abc", 1) // "bcd"
caesar("xyz", 3) // "abc" (wraps round to the start)
caesar("Meet at 5pm, Harare!", 2) // "Oggv cv 5ro, Jctctg!"
caesar("khoor", -3) // "hello" (negative shifts go backwards)
caesar("abc", 27) // "bcd" (27 is a full lap plus 1)
Rules
- Lowercase letters stay lowercase, capitals stay capitals.
- Anything that is not a letter (spaces, digits, punctuation) stays exactly as it is.
- After
zcomesaagain, and beforeacomesz. - The shift can be any whole number: 0, negative, or bigger than 26.
Tips
- Keep the alphabet in a string:
const lower = "abcdefghijklmnopqrstuvwxyz";. Thenlower.indexOf("c")is 2 andlower[2]is"c". - Build the answer one character at a time in a loop, adding to a result string.
%gives the remainder, which is perfect for wrapping round:(23 + 3) % 26is 0, the position ofa.- Careful: in JavaScript,
-1 % 26is-1, not 25.((n % 26) + 26) % 26always lands between 0 and 25.