Lesson 1 of 8 · 12 min

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 z comes a again, and before a comes z.
  • The shift can be any whole number: 0, negative, or bigger than 26.

Tips

  • Keep the alphabet in a string: const lower = "abcdefghijklmnopqrstuvwxyz";. Then lower.indexOf("c") is 2 and lower[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) % 26 is 0, the position of a.
  • Careful: in JavaScript, -1 % 26 is -1, not 25. ((n % 26) + 26) % 26 always lands between 0 and 25.
main.js
function caesar(text, shift) {
  // TODO: move every letter `shift` places along the alphabet
  return text;
}

console.log(caesar("hello", 3));   // should print khoor
console.log(caesar("khoor", -3));  // should print hello

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…