Skip to content

Commit 9103435

Browse files
committed
Fix performance bug and add Unicode test
1 parent cff0f16 commit 9103435

File tree

2 files changed

+27
-17
lines changed

2 files changed

+27
-17
lines changed

Conversions/ArbitraryBase.js

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,16 @@
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+
114
/**
215
* Converts a string from one base to other
316
* @param {string} stringInBaseOne String in input base
@@ -33,24 +46,11 @@ const convertArbitraryBase = (stringInBaseOne, baseOneCharacterString, baseTwoCh
3346
let stringInBaseTwo = ''
3447
const stringTwoBase = baseTwoCharacters.length
3548
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
3952
}
40-
const baseTwoZero = baseTwoCharacters.at(0)
41-
return stringInBaseTwo.replace(new RegExp(`^${baseTwoZero}+`, 'u'), '')
53+
return stringInBaseTwo || baseTwoCharacters[0]
4254
}
4355

4456
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-
// '🎸💝🎸🦄🦄'

Conversions/test/ArbitraryBase.test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,13 @@ test('Check the answer of convertArbitraryBase(111, 0123456789, abcdefgh) is bfh
3434
const res = convertArbitraryBase('111', '0123456789', 'abcdefgh')
3535
expect(res).toBe('bfh')
3636
})
37+
38+
test('Unicode awareness', () => {
39+
const res = convertArbitraryBase('98', '0123456789', '💝🎸🦄')
40+
expect(res).toBe('🎸💝🎸🦄🦄')
41+
})
42+
43+
test('zero', () => {
44+
const res = convertArbitraryBase('0', '0123456789', 'abc')
45+
expect(res).toBe('a')
46+
})

0 commit comments

Comments
 (0)