-
Notifications
You must be signed in to change notification settings - Fork 0
/
short.js
56 lines (51 loc) · 1.44 KB
/
short.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
function strtodec(str) {
let eq = [];
for (let index = 0; index < str.length; index++) {
eq.push(str.charCodeAt(index) - 96);
}
let res = eq[0] * 27 + eq[1];
for (let i = 2; i < eq.length; i++) {
res = res * 27 + eq[i];
}
return res;
}
function dectostr(num) {
let res = [];
while (num > 0) {
res.push(num % 27 + 96);
num = parseInt(num / 27);
}
res.reverse();
let ans = '';
res.forEach(element => {
ans += String.fromCharCode(element);
});
return ans;
}
function encoder(num) {
const possibilities = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
num = strtodec(num);
let res = '';
while (num > 0) {
res += possibilities[num % 62];
num = parseInt(num / 62);
}
return res.split("").reverse().join("");
}
function decoder(encoded) {
const possibilities = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
q = encoded.split('');
index = [];
q.forEach(element => {
index.push(possibilities.indexOf(element));
});
let res = index[0] * 62 + index[1];
for (let i = 2; i < index.length; i++) {
res = res * 62 + index[i];
}
return dectostr(res);
}
console.log(encoder('helloworld')); //hLbcYETu
console.log(decoder('hLbcYETu')); //helloworld
//length of helloworld is 10
//length of hLbcYETu is 8