Skip to content

Commit f16b7b2

Browse files
committed
Complete caesars cipher
1 parent e26d6ff commit f16b7b2

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export function rot13(str) {
2+
// A = 0 , Z = 25
3+
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4+
let decoded = [];
5+
for (let i = 0; i < str.length; i += 1) {
6+
if (/\W/.test(str[i])) {
7+
decoded.push(str[i]);
8+
continue;
9+
}
10+
const startIndex = alphabet.indexOf(str[i]);
11+
const newIndex = startIndex + 13 <= 25 ? startIndex + 13 : (startIndex + 13) - 26;
12+
decoded.push(alphabet[newIndex]);
13+
}
14+
return decoded.join('');
15+
}

src/fcc-course-projects/fcc_course_projects.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,31 @@ export function convertToRoman(num) {
5151
return romanNumeral;
5252
}
5353
```
54+
55+
#### Caesars Cipher
56+
57+
One of the simplest and most widely known ciphers is a Caesar cipher, also known as a shift cipher. In a shift cipher the meanings of the letters are shifted by some set amount.
58+
59+
A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus `'A' ↔ 'N', 'B' ↔ 'O'` and so on.
60+
61+
Write a function which takes a ROT13 encoded string as input and returns a decoded string.
62+
63+
All letters will be uppercase. Do not transform any non-alphabetic character (i.e. spaces, punctuation), but do pass them on.
64+
65+
```javascript
66+
export function rot13(str) {
67+
// A = 0 , Z = 25
68+
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
69+
let decoded = [];
70+
for (let i = 0; i < str.length; i += 1) {
71+
if (/\W/.test(str[i])) {
72+
decoded.push(str[i]);
73+
continue;
74+
}
75+
const startIndex = alphabet.indexOf(str[i]);
76+
const newIndex = startIndex + 13 <= 25 ? startIndex + 13 : (startIndex + 13) - 26;
77+
decoded.push(alphabet[newIndex]);
78+
}
79+
return decoded.join('');
80+
}
81+
```
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { rot13 } from "../../src/fcc-course-projects/caesars_cipher";
2+
3+
test('should decode caesars cipher', () => {
4+
expect(rot13("SERR PBQR PNZC!")).toBe("FREE CODE CAMP!");
5+
});

0 commit comments

Comments
 (0)