forked from TheOdinProject/javascript-exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaesar.js
35 lines (30 loc) · 840 Bytes
/
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
const caesar = function(string, shift) {
let result=''
for (i = 0; i < string.length; i++) {
result += shiftChar(string.charCodeAt(i), shift)
}
return result
}
const lowerA = 'a'.charCodeAt(0)
const lowerZ = 'z'.charCodeAt(0)
const upperA = 'A'.charCodeAt(0)
const upperZ = 'Z'.charCodeAt(0)
function shiftChar(charCode, shift) {
let shiftBase
if (upperA <= charCode && charCode <= upperZ) {
shiftBase = upperA
} else if (lowerA <= charCode && charCode <= lowerZ) {
shiftBase = lowerA
}
if (shiftBase) {
charCode = (charCode + shift)
while (charCode < shiftBase) {
charCode += 26
}
while (charCode >= (shiftBase + 26)) {
charCode -= 26
}
}
return String.fromCharCode(charCode)
}
module.exports = caesar