Skip to content

Commit

Permalink
Add base62 encode/decode to Misc.js
Browse files Browse the repository at this point in the history
  • Loading branch information
ItsOnlyBinary committed Aug 29, 2023
1 parent 3efbcb3 commit f0d8e99
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/helpers/Misc.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
24 changes: 24 additions & 0 deletions tests/unit/Misc.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
});
});

0 comments on commit f0d8e99

Please sign in to comment.