|
| 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 } |
0 commit comments