Last active
August 30, 2019 06:44
-
-
Save CatsMiaow/7fc9f28c9d2a5ab6d7605646086fdca6 to your computer and use it in GitHub Desktop.
BigNumber Base62 Encoding
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
import * as assert from 'assert'; | |
import BigNumber from 'bignumber.js'; | |
class Base62 { | |
private readonly base: BigNumber = new BigNumber(62); | |
private readonly charset: string[] = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); | |
public encode(integer: string): string { | |
if (Number(integer) === 0) { | |
return '0'; | |
} | |
let num: BigNumber = new BigNumber(integer); | |
let str: string[] = []; | |
while (num.gt(0)) { | |
str = [this.charset[num.mod(this.base).toNumber()], ...str]; | |
num = num.div(this.base).integerValue(BigNumber.ROUND_FLOOR); | |
} | |
return str.join(''); | |
} | |
public decode(str: string): string { | |
return str.split('').reverse().reduce( | |
(prev: BigNumber, char: string, i: number) => | |
this.base.pow(i).times(this.charset.indexOf(char)).plus(prev), | |
new BigNumber(0)).toFixed(); | |
} | |
} | |
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) { | |
assert.strictEqual(numstr, base62.decode(base62.encode(numstr))); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment