-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcaesar-cipher.js
More file actions
33 lines (27 loc) · 761 Bytes
/
Copy pathcaesar-cipher.js
File metadata and controls
33 lines (27 loc) · 761 Bytes
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
/**
* @title Caesar Cipher
* @difficulty Easy
* @link https://www.hackerrank.com/challenges/caesar-cipher-1/problem
*/
const caesarCipher = (letters, shift) => {
const range = 'Z'.charCodeAt(0) - 'A'.charCodeAt(0) + 1;
const shiftMod = shift % range;
const ret = [...letters].map(letter => {
if (/[a-z]/.test(letter)) {
let moved = letter.charCodeAt(0) + shiftMod;
if (moved > 'z'.charCodeAt(0)) {
moved -= range;
}
return String.fromCharCode(moved);
}
if (/[A-Z]/.test(letter)) {
let moved = letter.charCodeAt(0) + shiftMod;
if (moved > 'Z'.charCodeAt(0)) {
moved -= range;
}
return String.fromCharCode(moved);
}
return letter;
});
return ret.join('');
};