Write a Caesar cipher

“Caesar cipher”, a Black belt challenge from the CurlyScript Dojo. It uses what Grade 10: Array Power Tools: map, filter & reduce teaches, and 4 tests check your answer.

The challenge

Write caesar(text, shift) that shifts every lowercase letter forward in the alphabet by shift places, wrapping from z back to a. Leave everything else (spaces, punctuation) as it is.

Example
caesar("abc", 1)        // "bcd"
caesar("xyz", 3)        // "abc"
caesar("hi there!", 13) // "uv gurer!"

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • caesar("abc", 1) gives "bcd"
  • caesar("xyz", 3) gives "abc"
  • caesar("hi there!", 13) gives "uv gurer!"
  • Shifting by 5 then 21 gets the original back: caesar(caesar("secret", 5), 21) gives "secret"

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

const ALPHABET = "abcdefghijklmnopqrstuvwxyz"; and ALPHABET.indexOf(char) gives a letter’s position.

Hint 2

Wrap around with the remainder: (index + shift) % 26.

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function caesar(text, shift) {
  const ALPHABET = "abcdefghijklmnopqrstuvwxyz";
  let result = "";
  for (const char of text) {
    const i = ALPHABET.indexOf(char);
    result += i === -1 ? char : ALPHABET[(i + shift) % 26];
  }
  return result;
}

Learn what you need

This exercise uses what Grade 10: Array Power Tools: map, filter & reduce teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning