-
Notifications
You must be signed in to change notification settings - Fork 0
/
caesars-cipher.txt
47 lines (38 loc) · 1.06 KB
/
caesars-cipher.txt
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
38
39
40
41
42
43
44
45
46
47
function rot13(str) {
let codes = [];
let res = [];
let charCodes = [];
//find out the non-alphabetic character
const regex = /[\W]/ig;
let punc = str.matchAll(regex);
let arr = [...punc];
let indexes = arr.map(ele => ele.index)
//push UTF-16 codes + 13 of each letter
for(let i=0; i<str.length; i++) {
let code = str.charCodeAt(i);
codes.push(code+13);
}
//if code is bigger than 90, it's restarting from the beggining of alphabet
codes.forEach(code => {
if(code > 90) {
let diff = code - 90;
diff+=64;
charCodes.push(diff);
} else {
charCodes.push(code);
}
})
for(let i=0; i<charCodes.length; i++) {
res.push(String.fromCharCode(charCodes[i]));
}
//put punctuation back
let strArr = str.split("");
for(let i=0; i<indexes.length; i++) {
res[indexes[i]] = strArr[indexes[i]];
}
console.log(res.join(""));
return res.join("");
}
let str = "Jul qvq gur puvpxra pebff gur ebnq?";
rot13(str.toUpperCase());
rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.")