From f0d8e99b7e7f9407cc267e07bcd2f55e87c19b4d Mon Sep 17 00:00:00 2001 From: ItsOnlyBinary Date: Tue, 29 Aug 2023 20:11:11 +0100 Subject: [PATCH] Add base62 encode/decode to Misc.js --- src/helpers/Misc.js | 32 ++++++++++++++++++++++++++++++++ tests/unit/Misc.spec.js | 24 ++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/src/helpers/Misc.js b/src/helpers/Misc.js index 4151d5891..0b2f5aca4 100644 --- a/src/helpers/Misc.js +++ b/src/helpers/Misc.js @@ -399,3 +399,35 @@ export function strCompare(a, b) { 1 : -1; } + +const base62Digits = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; +export function base62Encode(_int) { + let int = _int; + let result = ''; + + if (int === 0) { + return base62Digits[0]; + } + + while (int > 0) { + result = base62Digits[int % base62Digits.length] + result; + int = Math.floor(int / base62Digits.length); + } + + return result; +} + +export function base62Decode(str) { + let result = 0; + + for (let i = 0; i < str.length; i++) { + const charIdx = base62Digits.indexOf(str[i]); + if (charIdx < 0) { + return NaN; + } + + result += charIdx * base62Digits.length ** (str.length - 1 - i); + } + + return result; +} diff --git a/tests/unit/Misc.spec.js b/tests/unit/Misc.spec.js index 30c66f258..17e1e1c6e 100644 --- a/tests/unit/Misc.spec.js +++ b/tests/unit/Misc.spec.js @@ -21,4 +21,28 @@ describe('Misc.js', () => { expect(doesMention).toEqual(c[2]); }); }); + + it('base64Encode and Decode should match', () => { + const tests = [ + [0, '0'], + [10, 'a'], + [61, 'Z'], + [62, '10'], + [55378008, '3KmlG'], + ]; + + tests.forEach(([key, value]) => { + const encoded = Misc.base62Encode(key); + const decoded = Misc.base62Decode(value); + expect(encoded).toEqual(value); + expect(decoded).toEqual(key); + }); + + for (let i = 0; i < 1000; i++) { + const random = Math.floor((Math.random() * 1000000)); + const encoded = Misc.base62Encode(random); + const decoded = Misc.base62Decode(encoded); + expect(decoded).toEqual(random); + } + }); });