Skip to content

Commit 1d81d40

Browse files
committed
refactor: refactor code in intToBase.js
1 parent be56ea7 commit 1d81d40

File tree

3 files changed

+34
-32
lines changed

3 files changed

+34
-32
lines changed
Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/**
2-
* @function hornerScheme
2+
* @function intToBase
33
* @description Convert a number from decimal system to another (till decimal)
44
* @param {Number} number Number to be converted
55
* @param {Number} base Base of new number system
@@ -12,27 +12,29 @@
1212
* const num2 = 125 // Needs to be converted to the octal number system
1313
* gornerScheme(num, 8); // ===> 175
1414
*/
15-
const hornerScheme = (number, base) => {
15+
const intToBase = (number, base) => {
1616
if (typeof number !== 'number' || typeof base !== 'number') {
1717
throw new Error('Input data must be numbers')
1818
}
1919
// Zero in any number system is zero
2020
if (number === 0) {
21-
return `${number}`
21+
return '0'
2222
}
2323
let absoluteValue = Math.abs(number)
2424
let convertedNumber = ''
2525
while (absoluteValue > 0) {
2626
// Every iteration last digit is taken away
27-
// and added to the previois one
27+
// and added to the previous one
2828
const lastDigit = absoluteValue % base
2929
convertedNumber = lastDigit + convertedNumber
3030
absoluteValue = Math.trunc(absoluteValue / base)
3131
}
3232
// Result is whether negative or positive,
3333
// depending on the original value
34-
const result = number < 0 ? `-${convertedNumber}` : convertedNumber
35-
return result
34+
if (number < 0) {
35+
convertedNumber = '-' + convertedNumber
36+
}
37+
return convertedNumber
3638
}
3739

38-
export { hornerScheme }
40+
export { intToBase }

Maths/test/HornerScheme.test.js

Lines changed: 0 additions & 25 deletions
This file was deleted.

Maths/test/intToBase.test.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { intToBase } from '../intToBase'
2+
3+
describe('Int to Base', () => {
4+
test('Conversion to the binary system', () => {
5+
expect(intToBase(210, 2)).toEqual('11010010')
6+
expect(intToBase(-210, 2)).toEqual('-11010010')
7+
})
8+
test('Conversion to the system with base 5', () => {
9+
expect(intToBase(210, 5)).toEqual('1320')
10+
expect(intToBase(-210, 5)).toEqual('-1320')
11+
})
12+
test('Conversion to the octal system', () => {
13+
expect(intToBase(210, 8)).toEqual('322')
14+
expect(intToBase(-210, 8)).toEqual('-322')
15+
})
16+
test('Output is 0', () => {
17+
expect(intToBase(0, 8)).toEqual('0')
18+
expect(intToBase(0, 8)).toEqual('0')
19+
})
20+
test('Throwing an exception', () => {
21+
expect(() => intToBase('string', 2)).toThrow()
22+
expect(() => intToBase(10, 'base')).toThrow()
23+
expect(() => intToBase(true, false)).toThrow()
24+
})
25+
})

0 commit comments

Comments
 (0)