diff --git a/__tests__/index.ts b/__tests__/index.ts index 2316831..bdb4a62 100644 --- a/__tests__/index.ts +++ b/__tests__/index.ts @@ -1,10 +1,11 @@ -import n32, { getSymbol } from '../dist'; +import n32, { n32decode, getSymbol, getSymbolValue } from '../dist'; describe('n32', () => { it('returns a valid string', () => { expect(n32(0)).toBe('0'); expect(n32(31)).toBe('z'); expect(n32(32)).toBe('10'); + expect(n32(1035280)).toBe('zk0g'); expect(n32(Number.MAX_SAFE_INTEGER)).toBe('7zzzzzzzzzz'); }); it('throws an error', () => { @@ -12,6 +13,16 @@ describe('n32', () => { }); }); +describe('n32decode', () => { + it('returns a valid number', () => { + expect(n32decode('0')).toBe(0); + expect(n32decode('z')).toBe(31); + expect(n32decode('10')).toBe(32); + expect(n32decode('0zk0g')).toBe(1035280); + expect(n32decode('7zzzzzzzzzz')).toBe(Number.MAX_SAFE_INTEGER); + }); +}); + describe('getSymbol', () => { it('returns a valid symbol', () => { expect(getSymbol(0)).toBe('0'); @@ -25,3 +36,12 @@ describe('getSymbol', () => { ); }); }); + +describe('getSymbolValue', () => { + it('returns a valid symbol value', () => { + expect(getSymbolValue('0')).toBe(0); + expect(getSymbolValue('9')).toBe(9); + expect(getSymbolValue('a')).toBe(10); + expect(getSymbolValue('z')).toBe(31); + }); +}); diff --git a/src/index.ts b/src/index.ts index 2ab0505..afdb88b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,6 +6,10 @@ export const getSymbol = (index: number): string => { return SYMBOLS.charAt(index); }; +export const getSymbolValue = (symbol: string): number => { + return '0123456789abcdefghjkmnpqrstvwxyz'.search(symbol); +}; + const n32 = (number: number): string => { if (number < 0) throw new Error('n32 expects an absolute number.'); if (number < 32) return getSymbol(number); @@ -22,4 +26,18 @@ const n32 = (number: number): string => { return m; }; +export const n32decode = (n32: string): number => { + const BASE = 32; + let n = n32.length; + let s = 0; + + while (n > 0) { + n--; + const symbol = n32[n32.length - n - 1]; + s = getSymbolValue(symbol) * BASE ** n + s; + } + + return s; +}; + export default n32;