-
Notifications
You must be signed in to change notification settings - Fork 642
/
Copy pathscript.js
49 lines (44 loc) · 1.57 KB
/
script.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
function main(x) { // x identifies from which button call is being made: Encrypt or Decrypt
var entry_text = document.getElementById('entry').value
var key_val = parseInt(document.getElementById('key').value) // Reading and storing both the inputs
// if (key_val < 0) {
// alert("Key value cannot be negative")
// }
key_val = key_val % 26
if (x === 2) {
key_val = (-1) * key_val // If call is for Decrypt then key value entered becomes negative
}
var final_string = ""
for (var i = 0; i < entry_text.length; i++) {
final_string = final_string + change(entry_text.charAt(i), key_val)
}
out_ele = document.getElementById('output')
out_ele.style.display = final_string === "" ? "none" : "flex"
out_ele.innerHTML = final_string
}
function isUpperCase(str) { // function to check if letter/word is uppercase or not
return str === str.toUpperCase()
}
function change(ch, key) { // function to shift alphabets according to the key value
if (!(/[a-zA-Z]/).test(ch)) { // checks for symbol and returns without any change if found
return ch
}
if (isUpperCase(ch)) {
let no = (ch.charCodeAt(0) + key - 65) % 26 + 65
if (no < 65) {
return (String.fromCharCode(no + 26))
}
else {
return (String.fromCharCode(no))
}
}
else {
let no = (ch.charCodeAt(0) + key - 97) % 26 + 97
if (no < 97) {
return (String.fromCharCode(no + 26))
}
else {
return (String.fromCharCode(no))
}
}
}