-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcaesarCipher.js
More file actions
37 lines (28 loc) · 948 Bytes
/
caesarCipher.js
File metadata and controls
37 lines (28 loc) · 948 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
28
29
30
31
32
33
34
35
36
37
function caeasarCipher (str, num) {
num = num % 26;
const lowerCaseStr = str.toLowerCase();
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
let newString = '';
for (let index = 0; index < lowerCaseStr.length; index++) {
const currentLetter = lowerCaseStr[index];
if (currentLetter === ' ') {
newString += currentLetter;
continue;
}
const currentIndex = alphabet.indexOf(currentLetter);
let newIndex = currentIndex + num;
if (newIndex > 25) {
newIndex = newIndex - 26;
}
if (newIndex < 0) {
newIndex = 26 + newIndex;
}
if (str[index] === str[index].toUpperCase()) {
newString += alphabet[newIndex].toUpperCase();
} else {
newString += alphabet[newIndex];
}
}
return newString;
}
console.log(caeasarCipher('Javascript', -900));