Skip to content

Instantly share code, notes, and snippets.

@mattlubner
Forked from kevinyan815/base62.js
Last active October 14, 2020 20:46
Show Gist options
  • Save mattlubner/19aba0e7a40eb2be68726e4b24aec66c to your computer and use it in GitHub Desktop.
Save mattlubner/19aba0e7a40eb2be68726e4b24aec66c to your computer and use it in GitHub Desktop.
BigInt-compatible Base62 Conversion Functions
// requires ES2020 for BigInt support
const digits = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
function toBase62(number) {
if (number === 0n) {
return '0';
}
let result = '';
let remaining = number;
while (remaining > 0n) {
result = digits[Number(remaining % 62n)] + result;
remaining = remaining / 62n;
}
return result;
}
function fromBase62(string) {
const length = BigInt(string.length);
return [...string].reduce((accumulator, character, index) => {
const decodedCharacter = BigInt(digits.indexOf(character));
if (decodedCharacter < 0) {
throw new Error('Input string contained non-base62 characters');
}
return (
accumulator + decodedCharacter * 62n ** (length - BigInt(index) - 1n)
);
}, 0n);
}
const digits = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
function toBase62(number: bigint): string {
if (number === 0n) {
return '0';
}
let result = '';
let remaining = number;
while (remaining > 0n) {
result = digits[Number(remaining % 62n)] + result;
remaining = remaining / 62n;
}
return result;
}
function fromBase62(string: string): bigint {
const length = BigInt(string.length);
return [...string].reduce(
(accumulator: bigint, character: string, index: number): bigint => {
const decodedCharacter = BigInt(digits.indexOf(character));
if (decodedCharacter < 0) {
throw new Error('Input string contained non-base62 characters');
}
return (
accumulator + decodedCharacter * 62n ** (length - BigInt(index) - 1n)
);
},
0n,
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment