base62
This does base62 encoding and decoding
Created by: hackvertor
Installed 1 times
Category: Convert
Created on: Thursday, October 10, 2024 at 11:52:34 AM
Updated on: Thursday, October 10, 2024 at 11:52:34 AM
Tag arguments
[]
Code
class base62 {
encode(input) {
const alphabet =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
let buffer = BigInt(
"0x" +
[...input]
.map((c) => c.charCodeAt(0).toString(16).padStart(2, "0"))
.join(""),
);
let encoded = "";
while (buffer > 0) {
const remainder = buffer % 62n;
buffer = buffer / 62n;
encoded = alphabet[Number(remainder)] + encoded;
}
return encoded;
}
decode(input) {
const alphabet =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
let buffer = BigInt(0);
for (let char of input) {
buffer = buffer * 62n + BigInt(alphabet.indexOf(char));
}
const hex = buffer.toString(16);
return (
hex
.match(/.{1,2}/g)
?.map((byte) => String.fromCharCode(parseInt(byte, 16)))
.join("") ?? ""
);
}
matches(input) {
const base62Regex = /^[0-9A-Za-z]{10,}$/;
const result = base62Regex.exec(input);
return result ? result : null;
}
}