File tree Expand file tree Collapse file tree 2 files changed +65
-0
lines changed
Expand file tree Collapse file tree 2 files changed +65
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @function intToBase
3+ * @description Convert a number from decimal system to another (till decimal)
4+ * @param {Number } number Number to be converted
5+ * @param {Number } base Base of new number system
6+ * @returns {String } Converted Number
7+ * @see [HornerMethod](https://en.wikipedia.org/wiki/Horner%27s_method)
8+ * @example
9+ * const num1 = 125 // Needs to be converted to the binary number system
10+ * gornerScheme(num, 2); // ===> 1111101
11+ * @example
12+ * const num2 = 125 // Needs to be converted to the octal number system
13+ * gornerScheme(num, 8); // ===> 175
14+ */
15+ const intToBase = ( number , base ) => {
16+ if ( typeof number !== 'number' || typeof base !== 'number' ) {
17+ throw new Error ( 'Input data must be numbers' )
18+ }
19+ // Zero in any number system is zero
20+ if ( number === 0 ) {
21+ return '0'
22+ }
23+ let absoluteValue = Math . abs ( number )
24+ let convertedNumber = ''
25+ while ( absoluteValue > 0 ) {
26+ // Every iteration last digit is taken away
27+ // and added to the previous one
28+ const lastDigit = absoluteValue % base
29+ convertedNumber = lastDigit + convertedNumber
30+ absoluteValue = Math . trunc ( absoluteValue / base )
31+ }
32+ // Result is whether negative or positive,
33+ // depending on the original value
34+ if ( number < 0 ) {
35+ convertedNumber = '-' + convertedNumber
36+ }
37+ return convertedNumber
38+ }
39+
40+ export { intToBase }
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