-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcipher.js
39 lines (32 loc) · 949 Bytes
/
cipher.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
module.exports.encode = function(str, key) {
let letters = str.toUpperCase().split('');
return letters.map( (letter) => {
let charCode = letter.charCodeAt(0);
if (charCode < 65 || charCode > 90 ) {
// Non-alphanumeric character
return String.fromCharCode(charCode);
}
else if (charCode + key > 90) {
return String.fromCharCode(charCode + key - 26);
}
else {
return String.fromCharCode(charCode + key);
}
}).join('');
};
module.exports.decode = function(str, key) {
let letters = str.split('');
return letters.map( (letter) => {
let charCode = letter.charCodeAt(0);
if (charCode < 65 || charCode > 90 ) {
// Non-alphanumeric character
return String.fromCharCode(charCode);
}
else if (charCode - key < 65) {
return String.fromCharCode(charCode - key + 26);
}
else {
return String.fromCharCode(charCode - key);
}
}).join('');
};