From 063d8ef9eaf874a941f4459e831057dd0a1b7ddd Mon Sep 17 00:00:00 2001 From: Joris Date: Tue, 5 Jul 2022 21:55:41 +0200 Subject: Rewrite in TS --- src/lib/base.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/lib/base.ts (limited to 'src/lib/base.ts') diff --git a/src/lib/base.ts b/src/lib/base.ts new file mode 100644 index 0000000..59c91cc --- /dev/null +++ b/src/lib/base.ts @@ -0,0 +1,32 @@ +export const b2: string[] = + '01'.split('') + +export const b16: string[] = + '0123456789abcdef'.split('') + +export const b62: string[] = + '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('') + +export function encode(n: bigint, charset: string[]): string { + const base = BigInt(charset.length) + + if (n == BigInt(0)) { + return '0' + } else { + var xs = [] + while (n > BigInt(0)) { + xs.push(charset[Number(n % base)]) + n = n / base + } + return xs.reverse().join('') + } +} + +export function decode(xs: string, charset: string[]): bigint { + const base = BigInt(charset.length) + + return xs + .split('') + .reverse() + .reduce((acc, x, i) => acc + (BigInt(charset.indexOf(x)) * (base ** BigInt(i))), BigInt(0)) +} -- cgit v1.2.3