forked from TheOdinProject/javascript-exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaesar.js
67 lines (60 loc) · 1.81 KB
/
caesar.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
// check if a character is lower case
const checkLoAlpha = (charCode) => {
return charCode >= 97 && charCode <= 122 ? true : false
}
//check if a character is uppercase
const checkUpAlpha = (charCode) => {
return charCode >= 65 && charCode <= 90 ? true : false
}
// returns new shifted character code
const newCharCode = (e, num) => {
const charCode = e.charCodeAt();
let newCharCode;
if (num > 0){
if (checkLoAlpha(charCode) && (charCode + num) > 122) { // lowercase letter alphabet rollover
newCharCode = charCode + num - 123 + 97;
while (newCharCode > 122) {
newCharCode = newCharCode - 123 +97;
}
return newCharCode;
} if (checkUpAlpha(charCode) && (charCode + num) > 90) { // uppercase letter alphabet rollover
newCharCode = charCode + num - 91 + 65;
while (newCharCode > 90) {
newCharCode = newCharCode - 91 + 65;
}
return newCharCode;
}
return charCode + num; // default -> no rollover needed
}
// num < 0
if (checkLoAlpha(charCode) && (charCode + num) < 97) {
newCharCode = charCode + num + 123 - 97;
while (newCharCode < 97) {
newCharCode = newCharCode + 123 - 97;
}
return newCharCode;
}
if (checkUpAlpha(charCode) && (charCode + num) < 65) {
newCharCode = charCode + num + 91 - 65;
while (newCharCode < 65) {
newCharCode = newCharCode + 91 - 65;
}
return newCharCode;
}
return charCode + num;
}
const caesar = function(str, num) {
const arr = str.split('');
const PUNCT_OR_SPACE = /[ .,'"?!()-]/
return arr.map(e => {
if (PUNCT_OR_SPACE.test(e)) {
return e
}
return String.fromCharCode(newCharCode(e, num))
}).join('')
}
module.exports = caesar
// console.log('a'.charCodeAt()) //97
// console.log('z'.charCodeAt()) //122
// console.log('A'.charCodeAt()) //65
// console.log('Z'.charCodeAt()) //90