-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecoder.js
38 lines (29 loc) · 961 Bytes
/
decoder.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
import zlib from "zlib";
import {baseChars} from "./baseChars.js";
function decodeJson(str) {
const singleNumber = decodeNumber(str);
const compressed = decodeNumberToBytes(singleNumber);
const buffer = Buffer.from(compressed);
const bytes = zlib.inflateRawSync(buffer);
return JSON.parse(bytes.toString('utf8'));
}
function decodeNumberToBytes(singleNumber) {
const backToBytes = [];
let singleNumberDuplicate = singleNumber;
while (singleNumberDuplicate > 0n) {
backToBytes.push(Number(singleNumberDuplicate & 255n));
singleNumberDuplicate >>= 8n;
}
return backToBytes.reverse();
}
function decodeNumber(str) {
const base = BigInt(baseChars.length);
let decoded = 0n;
for (let i = 0; i < str.length; i++) {
const char = str[i];
const index = baseChars.indexOf(char);
decoded = decoded * base + BigInt(index);
}
return decoded;
}
export {decodeJson};