-
-
Save mattlubner/19aba0e7a40eb2be68726e4b24aec66c to your computer and use it in GitHub Desktop.
BigInt-compatible Base62 Conversion Functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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