-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcipher.js
58 lines (52 loc) · 1.61 KB
/
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
53
54
55
56
57
58
/**
* @copyright 2019 Sam Price
* @description A Bacon Cipher
*/
const cipher = ['AAAAA','AAAAB','AAABA','AAABB','AABAA','AABAB','AABBA','AABBB','ABAAA','ABAAB','ABABA','ABABB','ABBAA','ABBAB','ABBBA','ABBBB','BAAAA','BAAAB','BAABA','BAABB','BABAA','BABAB','BABBA','BABBB','BBAAA','BBAAB'];
const orig = ['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'];
function encode(text = '') {
const final = [];
const split = text.split('');
for (let i = 0; i < split.length; i++) {
const char = split[i].toUpperCase();
if (orig.includes(char)) {
const index = orig.indexOf(char);
final.push(cipher[index]);
} else {
final.push(char);
}
}
return final.join('');
}
function decode(text = '', isTitleCase = true) {
const final = [];
const split = text.split('');
let charGroup = [];
for (let i = 0; i < split.length; i++) {
const char = split[i].toUpperCase();
if (/[AB]/.test(char)) {
if (charGroup.length === 4) {
charGroup.push(char)
const index = cipher.indexOf(charGroup.join(''));
final.push(orig[index]);
charGroup = [];
} else {
charGroup.push(char);
}
} else {
final.push(char);
}
}
return isTitleCase ? titleCase(final.join('')) : final.join('');
}
function titleCase(str = '') {
return str.toLowerCase().split(' ').map(word => {
return word.replace(word.charAt(0), word.charAt(0).toUpperCase());
}).join(' ');
}
const version = require('./package.json').version;
module.exports = {
encode,
decode,
version
}