-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcaesar-cipher.js
More file actions
27 lines (25 loc) · 774 Bytes
/
caesar-cipher.js
File metadata and controls
27 lines (25 loc) · 774 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function caesarChipher(text, shift) {
const output = [];
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (!isNaN(char)) {
output.push(char);
continue;
}
const charCode = char.charCodeAt(0);
// uppercase A - Z
if (charCode >= 65 && charCode <= 90) {
const diff = charCode - 65;
const newCharCode = ((diff + shift) % 26) + 65;
output.push(String.fromCharCode(newCharCode));
} else if (charCode >= 97 && charCode <= 122) {
const diff = charCode - 97;
const newCharCode = ((diff + shift) % 26) + 97;
output.push(String.fromCharCode(newCharCode));
} else {
output.push(char);
}
}
return output.join('');
}
console.log(caesarChipher('Samodan195 Ollyboy121', 3));