-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathrot13-1.js
56 lines (50 loc) · 1.62 KB
/
rot13-1.js
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
48
49
50
51
52
53
54
55
56
function rot13(message) {
// 65 - 90 uppercase letters
// 97 - 122 lowercase letters
// place to store the encoded string
let encoded = '';
// iterate over the message
for (let i = 0; i < message.length; i++) {
// get the char code for the current letter
const letter = message[i];
const charCode = message.charCodeAt(i);
// if it is within either range - shift by 13
if (charCode >= 65 && charCode <= 90) {
// append shifted letter to the encoded string
let newCharCode = charCode + 13;
if (newCharCode > 90) {
newCharCode = 64 + (newCharCode - 90);
}
encoded += String.fromCharCode(newCharCode);
} else if (charCode >= 97 && charCode <= 122) {
// append shifted letter to the encoded string
let newCharCode = charCode + 13;
if (newCharCode > 122) {
newCharCode = 96 + (newCharCode - 122);
}
encoded += String.fromCharCode(newCharCode);
} else {
// aappend current letter to encoded
encoded += letter;
}
}
return encoded;
}
function rot13(message) {
let encoded = '';
const jt = (code, minValue) => (code - minValue + 12) % 26 + minValue + 1;
for (let i = 0; i < message.length; i++) {
const letter = message[i];
const charCode = message.charCodeAt(i);
if (charCode >= 65 && charCode <= 90) {
encoded += String.fromCharCode(jt(charCode, 66));
} else if (charCode >= 97 && charCode <= 122) {
encoded += String.fromCharCode(jt(charCode, 97));
} else {
encoded += letter;
}
}
return encoded;
}
console.log(rot13('grfg'), 'test');
console.log(rot13('Grfg'), 'Test');