File tree Expand file tree Collapse file tree 3 files changed +34
-32
lines changed Expand file tree Collapse file tree 3 files changed +34
-32
lines changed Original file line number Diff line number Diff line change 1
1
/**
2
- * @function hornerScheme
2
+ * @function intToBase
3
3
* @description Convert a number from decimal system to another (till decimal)
4
4
* @param {Number } number Number to be converted
5
5
* @param {Number } base Base of new number system
12
12
* const num2 = 125 // Needs to be converted to the octal number system
13
13
* gornerScheme(num, 8); // ===> 175
14
14
*/
15
- const hornerScheme = ( number , base ) => {
15
+ const intToBase = ( number , base ) => {
16
16
if ( typeof number !== 'number' || typeof base !== 'number' ) {
17
17
throw new Error ( 'Input data must be numbers' )
18
18
}
19
19
// Zero in any number system is zero
20
20
if ( number === 0 ) {
21
- return ` ${ number } `
21
+ return '0'
22
22
}
23
23
let absoluteValue = Math . abs ( number )
24
24
let convertedNumber = ''
25
25
while ( absoluteValue > 0 ) {
26
26
// Every iteration last digit is taken away
27
- // and added to the previois one
27
+ // and added to the previous one
28
28
const lastDigit = absoluteValue % base
29
29
convertedNumber = lastDigit + convertedNumber
30
30
absoluteValue = Math . trunc ( absoluteValue / base )
31
31
}
32
32
// Result is whether negative or positive,
33
33
// 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
36
38
}
37
39
38
- export { hornerScheme }
40
+ export { intToBase }
Load Diff This file was deleted.
Original file line number Diff line number Diff line change
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
+ } )
You can’t perform that action at this time.
0 commit comments