-
Notifications
You must be signed in to change notification settings - Fork 0
/
cesar.js
47 lines (42 loc) · 1.64 KB
/
cesar.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
var mode = prompt('You want to encrypt or decrypt a text ?\n\n1 for encrypt\n2 for decrypt');
if (mode === '1') {
var 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', ' '];
var sentence = prompt('Enter the text you want to encrypt').split('');
var key = Number(prompt('Enter the key you want to use for encrypt your text'));
var result = '';
if ((key <= 0) || (key >= 27) || (isNaN(key))) {
document.write('Invalid key, please enter a number between 1 and 26');
} else {
for (var i = 0; i < sentence.length; i++) {
var c = sentence[i];
if (alphabet.indexOf(c) === 26) {
result += ' ';
} else {
var id = alphabet.indexOf(c) + key;
c = alphabet[id % 26];
result += c;
}
}
}
document.write(result.toUpperCase());
} else if (mode === '2') {
var 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', ' '];
var sentence = prompt('Enter the text you want to decrypt').split('');
var key = Number(prompt('Enter the key to decrypt the text'));
var result = '';
if ((key <= 0) || (key >= 27) || isNaN(key)) {
documet.write('Invalid key, please enter a number between 1 and 26');
} else {
for (var i = 0; i < sentence.length; i++) {
var c = sentence[i];
if (alphabet.indexOf(c) === 26) {
result += ' ';
} else {
var id = alphabet.indexOf(c) - key + 26;
c = alphabet[id % 26];
result += c;
}
}
}
document.write(result.toLowerCase());
}