Skip to content

Commit d8caed2

Browse files
committed
caesar-cipher solution
1 parent e2de14e commit d8caed2

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
const lower_array = ['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'];
2+
const upper_array = ['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'];
3+
4+
5+
function encode(word: string, shift: number) {
6+
let caesar: string = '';
7+
for (let i: number=0, new_code: number; i<word.length; i++) {
8+
if (upper_array.includes(word[i])) {
9+
new_code = (upper_array.indexOf(word[i]) + shift + 26) % 26;
10+
if (new_code < 0) {new_code += 26}
11+
caesar += upper_array[new_code];
12+
} else if (lower_array.includes(word[i])) {
13+
new_code = (lower_array.indexOf(word[i]) + shift + 26) % 26;
14+
if (new_code < 0) {new_code += 26}
15+
caesar += lower_array[new_code];
16+
} else {
17+
caesar += word[i];
18+
}
19+
}
20+
return caesar;
21+
}
22+
23+
24+
function decode(word: string, shift: number) {return encode(word, -shift)}
25+
26+
console.log(encode('Hello, World!', 7)); // => 'Olssv, Dvysk!'
27+
console.log(encode('I love pizza.', -7)); // => 'B ehox ibsst.'
28+
console.log(encode('HytyQapgnr kyicq qclqc. Qmkcrgkcq.', 50)); // => 'HytyQapgnr kyicq qclqc. Qmkcrgkcq.'
29+
console.log(encode('abc', 24)); // => 'yza'
30+
console.log('')
31+
console.log(decode('CxvxaaxfMneb Axltb!', 9)); // => 'TomorrowDevs Rocks!'
32+
console.log(decode('Gtdflw Defotz Nzop td rcple!!!', -15)); // => 'Visual Studio Code is great!!!'
33+
console.log(decode("Buj'i mhyju jxu syfxuh.", 120)); // => 'Let's write the cipher.'
34+
console.log(decode('Vriwzduh Hqjlqhhulqj', 3)); // => 'Software Engineering'

0 commit comments

Comments
 (0)