-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
rot13.js
86 lines (80 loc) · 2.76 KB
/
rot13.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
function rot13(str) {
// a place to store the deciphered text
let deciphered = '';
// iterate over the string
for (let i = 0; i < str.length; i++) {
const value = str[i];
const charCode = str.charCodeAt(i);
// if the current value is a character
if (charCode >= 65 && charCode <= 90) {
const cipherCode = (((charCode - 65) + 13) % 26) + 65;
deciphered += String.fromCharCode(cipherCode);
} else if (charCode >= 97 && charCode <= 122) {
const cipherCode = (((charCode - 97) + 13) % 26) + 97;
deciphered += String.fromCharCode(cipherCode);
} else {
deciphered += value;
}
}
return deciphered;
}
function rot13(str) {
return Array.prototype.reduce.call(str, (deciphered, value, i) => {
const charCode = str.charCodeAt(i);
if (charCode >= 65 && charCode <= 90) {
const cipherCode = (((charCode - 65) + 13) % 26) + 65;
return deciphered + String.fromCharCode(cipherCode);
} else if (charCode >= 97 && charCode <= 122) {
const cipherCode = (((charCode - 97) + 13) % 26) + 97;
return deciphered + String.fromCharCode(cipherCode);
} else {
return deciphered + value;
}
}, '');
}
function rot13(str) {
return Array.prototype.reduce.call(str, (deciphered, value, i) => {
const charCode = str.charCodeAt(i);
if (charCode >= 65 && charCode <= 90) {
if (charCode < 65 + 13) {
return deciphered + String.fromCharCode(charCode + 13);
} else {
return deciphered + String.fromCharCode(charCode - 13);
}
} else if (charCode >= 97 && charCode <= 122) {
if (charCode < 97 + 13) {
return deciphered + String.fromCharCode(charCode + 13);
} else {
return deciphered + String.fromCharCode(charCode - 13);
}
} else {
return deciphered + value;
}
}, '');
}
function rot13(str) {
return Array.prototype.reduce.call(str, (deciphered, value, i) => {
const charCode = str.charCodeAt(i);
if (charCode >= 65 && charCode <= 90) {
if (value < 'M') {
return deciphered + String.fromCharCode(charCode + 13);
} else {
return deciphered + String.fromCharCode(charCode - 13);
}
} else if (charCode >= 97 && charCode <= 122) {
if (value < 'm') {
return deciphered + String.fromCharCode(charCode + 13);
} else {
return deciphered + String.fromCharCode(charCode - 13);
}
} else {
return deciphered + value;
}
}, '');
}
// ALCA! 🎉
function rot13(s) {
return s.replace(/[a-zA-Z]/g, (m, _, __, c = m.charCodeAt(0), o = c >= 97 ? 97 : 65) => String.fromCharCode(o + (c - o + 13) % 26));
}
console.log(rot13('EBG13 rknzcyr.'), 'ROT13 example.');
console.log(rot13('This is my first ROT13 excercise!'), 'Guvf vf zl svefg EBG13 rkprepvfr!');