feat(tool): base converter

This commit is contained in:
Corentin Thomasset 2022-04-12 14:27:52 +02:00
parent 5cd9997a84
commit 034c686896
No known key found for this signature in database
GPG key ID: 3103EB5E79496F9C
5 changed files with 118 additions and 1 deletions

View file

@ -0,0 +1,20 @@
export function convertBase({ value, fromBase, toBase }: { value: string; fromBase: number; toBase: number }) {
const range = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'.split('');
const fromRange = range.slice(0, fromBase);
const toRange = range.slice(0, toBase);
let decValue = value
.split('')
.reverse()
.reduce((carry: number, digit: string, index: number) => {
if (!fromRange.includes(digit)) {
throw new Error('Invalid digit `' + digit + '` for base ' + fromBase + '.');
}
return (carry += fromRange.indexOf(digit) * Math.pow(fromBase, index));
}, 0);
let newValue = '';
while (decValue > 0) {
newValue = toRange[decValue % toBase] + newValue;
decValue = (decValue - (decValue % toBase)) / toBase;
}
return newValue || '0';
}