|
1 |
| -export function convertBase({ value, fromBase, toBase }: { value: string; fromBase: number; toBase: number }) { |
| 1 | +export function hasNumberPrefix(value: string) { |
| 2 | + return (value ?? '').trim().match(/^(0[xob].|&[hob].)/i); |
| 3 | +} |
| 4 | + |
| 5 | +export function convertBase( |
| 6 | + { |
| 7 | + value, fromBase, toBase, |
| 8 | + ignorePunctuationsRegexChars = ' \u00A0_\.,-', |
| 9 | + handlePrefixSuffix = true, |
| 10 | + ignoreCase = true, |
| 11 | + }: { |
| 12 | + value: string |
| 13 | + fromBase: number |
| 14 | + toBase: number |
| 15 | + ignorePunctuationsRegexChars?: string |
| 16 | + handlePrefixSuffix?: boolean |
| 17 | + ignoreCase?: boolean |
| 18 | + }) { |
| 19 | + let cleanedValue = (value ?? '0').trim(); |
| 20 | + if (ignorePunctuationsRegexChars) { |
| 21 | + cleanedValue = cleanedValue.replace(new RegExp(`[${ignorePunctuationsRegexChars}]`, 'g'), ''); |
| 22 | + } |
| 23 | + let finalFromBase = fromBase; |
| 24 | + if (handlePrefixSuffix) { |
| 25 | + for (const regBase of [ |
| 26 | + { base: 2, regex: /^(&b|0b)?([01]+)([IULZn]*)$/i }, |
| 27 | + { base: 8, regex: /^(&o|0o)?([0-7]+)([IULZn]*)$/i }, |
| 28 | + { base: 16, regex: /^(&h|0x)?([a-f0-9]+)([IULZn]*)$/i }, |
| 29 | + ]) { |
| 30 | + const match = cleanedValue.match(regBase.regex); |
| 31 | + if (match) { |
| 32 | + if (match[1]) { |
| 33 | + finalFromBase = regBase.base; |
| 34 | + } |
| 35 | + cleanedValue = match[2]; |
| 36 | + break; |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + if (ignoreCase && finalFromBase <= 36) { |
| 41 | + cleanedValue = cleanedValue.toLowerCase(); |
| 42 | + } |
2 | 43 | const range = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'.split('');
|
3 |
| - const fromRange = range.slice(0, fromBase); |
| 44 | + const fromRange = range.slice(0, finalFromBase); |
4 | 45 | const toRange = range.slice(0, toBase);
|
5 |
| - let decValue = value |
| 46 | + let decValue = cleanedValue |
6 | 47 | .split('')
|
7 | 48 | .reverse()
|
8 | 49 | .reduce((carry: number, digit: string, index: number) => {
|
9 | 50 | if (!fromRange.includes(digit)) {
|
10 |
| - throw new Error(`Invalid digit "${digit}" for base ${fromBase}.`); |
| 51 | + throw new Error(`Invalid digit "${digit}" for base ${finalFromBase}.`); |
11 | 52 | }
|
12 |
| - return (carry += fromRange.indexOf(digit) * fromBase ** index); |
| 53 | + return (carry += fromRange.indexOf(digit) * finalFromBase ** index); |
13 | 54 | }, 0);
|
14 | 55 | let newValue = '';
|
15 | 56 | while (decValue > 0) {
|
|
0 commit comments