Boss lesson · Unit 03
A text toolkit
Three small functions built and tested: a palindrome check, a vowel counter, a Caesar shift
What you practise
- Small functions built and combined: a palindrome check, a vowel counter, a Caesar shift, each checked against answers you know
Try a question from this lesson
Pick one
A palindrome reads the same backwards: level, noon. First tool needed: reversing a word. What does this print?
let rev = "";
for (const ch of "abc") {
rev = ch + rev;
}
console.log(rev);Hint
Trace it. Each new character is joined on at the front of what is there so far.
Correct answer
cba
Why
Each character is put in front of what has been built so far: a, then ba, then cba. Writing rev + ch instead would add at the end and rebuild the word unchanged.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Positions in a string
The characters of a string are numbered from 0.
word.length is the number of characters. word[0] is the first one, and word[word.length - 1] is the last.
word.indexOf("d") goes the other way: it gives the position of a character, or -1 when it is not in the string.
const word = "code";
console.log(word.length); // 4
console.log(word[0]); // c
console.log(word.indexOf("d")); // 2
console.log(word.indexOf("x")); // -1Concept
A Caesar shift
A Caesar shift hides a message by replacing each letter with the one a few places later in the alphabet. After z it wraps around to a.
Find the letter's position, add the shift, and wrap with % 26: the remainder brings 26 back to 0 and 27 back to 1.
Then read the letter at the new position.
const abc = "abcdefghijklmnopqrstuvwxyz";
const i = abc.indexOf("y"); // 24
const j = (i + 3) % 26; // 1
console.log(abc[j]); // b10 more exercises in the app
- 1× order the lines
- 2× fill the blanks
- 3× multiple choice
- 3× type the answer
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.