Skip to content

Instantly share code, notes, and snippets.

@CatsMiaow
Last active June 1, 2024 11:30
Show Gist options
  • Save CatsMiaow/b479e96d5613dbd4711ab6d768b3eea0 to your computer and use it in GitHub Desktop.
Save CatsMiaow/b479e96d5613dbd4711ab6d768b3eea0 to your computer and use it in GitHub Desktop.
BigInt Base62 Encoding
import * as assert from 'assert';
/**
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt
*/
export class Base62 {
private readonly base: bigint = BigInt(62);
private readonly charset: string[] = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
public encode(integer: string): string {
if (Number(integer) === 0) {
return '0';
}
let num: bigint = BigInt(integer);
let str: string[] = [];
while (num > 0) {
str = [this.charset[num % this.base], ...str];
num = num / this.base;
}
return str.join('');
}
public decode(str: string): string {
return str.split('').reverse().reduce(
(prev: bigint, char: string, i: number) =>
prev + (BigInt(this.charset.indexOf(char)) * (this.base ** BigInt(i))),
BigInt(0)).toString();
}
}
export const base62: Base62 = new Base62();
// Test
const numbers: string[] = [
'0', '1', '2', '3', '4', '5', '1234567890', '9876543210',
'616580508813361172', '616580508813361200', '793548328091516928',
'24809234902840923840294829048204', '90275980235738905734980573490857'];
for (const numstr of numbers) {
const encode: string = base62.encode(numstr);
console.log(numstr, encode);
assert.strictEqual(numstr, base62.decode(encode));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment