-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshift-cipher.js
52 lines (51 loc) · 1.7 KB
/
shift-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
40
41
42
43
44
45
46
47
48
49
50
51
52
// create ShiftCipher class
class ShiftCipher {
constructor(num) {
this.shiftNum = num;
}
encrypt(string) {
string = string.toLowerCase();
let newString = '';
for (let i = 0; i < string.length; i++) {
//if is a lowerase letter
if (string.charCodeAt(i) > 96 && string.charCodeAt(i) < 123) {
// shift by 2
let shiftedChar = (string.charCodeAt(i) + this.shiftNum);
// wrap char around wile greater than z
while (shiftedChar > 122) {
let amountToShift = shiftedChar - 122;
shiftedChar = 97 + (amountToShift - 1);
}
// convert to letter and add to array
newString += String.fromCharCode(shiftedChar);
} else {
newString += String.fromCharCode(string.charCodeAt(i));
}
}
return newString.toUpperCase();
}
decrypt(string) {
string = string.toLowerCase();
let newString = '';
for (let i = 0; i < string.length; i++) {
//if is a lowerase letter
if (string.charCodeAt(i) > 96 && string.charCodeAt(i) < 123) {
// shift by 2
let shiftedChar = (string.charCodeAt(i) - this.shiftNum);
// wrap char around wile greater than z
while (shiftedChar < 97) {
let amountToShift = 97 - shiftedChar;
shiftedChar = 122 - (amountToShift - 1);
}
// convert to letter and add to array
newString += String.fromCharCode(shiftedChar);
} else {
newString += String.fromCharCode(string.charCodeAt(i));
}
}
return newString;
}
}
const cipher = new ShiftCipher(2);
console.log(cipher.encrypt('I love to code!')); // returns 'K NQXG VQ EQFG!'
console.log(cipher.decrypt('K <3 OA RWRRA')); // returns 'i <3 my puppy'