-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.caesarcypher.js
More file actions
40 lines (35 loc) · 1 KB
/
string.caesarcypher.js
File metadata and controls
40 lines (35 loc) · 1 KB
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
/*
* @title: caesarCipher
* @description: translate each letter k steps
* @author: Thorsten Kober
* @email: [email protected]
*/
function caesarCipher(string, k) {
const alphabet = [
'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x',
'y', 'z'];
const input = string.toLowerCase();
const result = [];
for (let i = 0; i < input.length; i++) {
const letter = input[i];
let index = alphabet.indexOf(letter);
if (index === -1) {
result.push(letter);
} else {
index += k % 26;
if (index > 25) index -= 26;
if (index < 0) index += 26;
const temp = string[i] === string[i].toUpperCase()
? alphabet[index].toUpperCase() : alphabet[index];
result.push(temp);
}
}
return result.join('');
}
// npx jest algorithms/string/string.caesarcypher.js
test('caesarCipher()', () => {
expect(caesarCipher('I love JavaScript!', 100)).toEqual('E hkra FwrwOynelp!');
});