|
| 1 | +/** |
| 2 | +* Divide two numbers and get the result of floor division and remainder |
| 3 | +* @param {number} dividend |
| 4 | +* @param {number} divisor |
| 5 | +* @returns {[result: number, remainder: number]} |
| 6 | +*/ |
| 7 | +const floorDiv = (dividend, divisor) => { |
| 8 | + const remainder = dividend % divisor |
| 9 | + const result = Math.floor(dividend / divisor) |
| 10 | + |
| 11 | + return [result, remainder] |
| 12 | +} |
| 13 | + |
1 | 14 | /**
|
2 | 15 | * Converts a string from one base to other
|
3 | 16 | * @param {string} stringInBaseOne String in input base
|
@@ -33,24 +46,11 @@ const convertArbitraryBase = (stringInBaseOne, baseOneCharacterString, baseTwoCh
|
33 | 46 | let stringInBaseTwo = ''
|
34 | 47 | const stringTwoBase = baseTwoCharacters.length
|
35 | 48 | while (value > 0) {
|
36 |
| - const remainder = value % stringTwoBase |
37 |
| - stringInBaseTwo = baseTwoCharacters.at(remainder) + stringInBaseTwo |
38 |
| - value /= stringTwoBase |
| 49 | + const [divisionResult, remainder] = floorDiv(value, stringTwoBase) |
| 50 | + stringInBaseTwo = baseTwoCharacters[remainder] + stringInBaseTwo |
| 51 | + value = divisionResult |
39 | 52 | }
|
40 |
| - const baseTwoZero = baseTwoCharacters.at(0) |
41 |
| - return stringInBaseTwo.replace(new RegExp(`^${baseTwoZero}+`, 'u'), '') |
| 53 | + return stringInBaseTwo || baseTwoCharacters[0] |
42 | 54 | }
|
43 | 55 |
|
44 | 56 | export { convertArbitraryBase }
|
45 |
| - |
46 |
| -// > convertArbitraryBase('98', '0123456789', '01234567') |
47 |
| -// '142' |
48 |
| - |
49 |
| -// > convertArbitraryBase('98', '0123456789', 'abcdefgh') |
50 |
| -// 'bec' |
51 |
| - |
52 |
| -// > convertArbitraryBase('129', '0123456789', '01234567') |
53 |
| -// '201' |
54 |
| - |
55 |
| -// > convertArbitraryBase('98', '0123456789', '💝🎸🦄') |
56 |
| -// '🎸💝🎸🦄🦄' |
0 commit comments