-
Notifications
You must be signed in to change notification settings - Fork 5
/
encrypt.js
37 lines (30 loc) · 977 Bytes
/
encrypt.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
/* ==========================================================================
*
* Use:
* 'Hello World!'.encrypt('mysecretkey')
* => 'Zijvw Gnhvh!'
*
* ========================================================================== */
String.prototype.encrypt = function(key) {
function between(x, min, max) {return x >= min && x <= max;}
let msg = [];
let output = '';
for (let char of this) {
let code = char.charCodeAt(0)
if (between(code, 65, 90)) {msg.push([code - 65, 0])}
else if (between(code, 97, 122)) {msg.push([code - 97, 1])}
else {msg.push(char)}
}
key = key.toLowerCase().split('').map(function(c) {
return c.charCodeAt(0) - 65
})
for (var i = 0; i < msg.length; i++) {
if (typeof msg[i] === 'string') {output += msg[i]}
else {
let value = (msg[i][0] + key[i % key.length]) % 26
output += String.fromCharCode(value + 65 + msg[i][1] * 32)
}
}
return output
}
module.exports = (text, key) => text.encrypt(key)