From 35e1fe68d0d6e8be2c2cfdc4dd581faa5128b7e2 Mon Sep 17 00:00:00 2001 From: Alex Popov Date: Mon, 31 Oct 2022 19:49:14 +0300 Subject: [PATCH] algorithm: add IntToBase algo and a test for it (#1258) --- Maths/IntToBase.js | 40 ++++++++++++++++++++++++++++++++++++ Maths/test/IntToBase.test.js | 25 ++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 Maths/IntToBase.js create mode 100644 Maths/test/IntToBase.test.js diff --git a/Maths/IntToBase.js b/Maths/IntToBase.js new file mode 100644 index 000000000..6ec8a0bab --- /dev/null +++ b/Maths/IntToBase.js @@ -0,0 +1,40 @@ +/** + * @function intToBase + * @description Convert a number from decimal system to another (till decimal) + * @param {Number} number Number to be converted + * @param {Number} base Base of new number system + * @returns {String} Converted Number + * @see [HornerMethod](https://en.wikipedia.org/wiki/Horner%27s_method) + * @example + * const num1 = 125 // Needs to be converted to the binary number system + * gornerScheme(num, 2); // ===> 1111101 + * @example + * const num2 = 125 // Needs to be converted to the octal number system + * gornerScheme(num, 8); // ===> 175 + */ +const intToBase = (number, base) => { + if (typeof number !== 'number' || typeof base !== 'number') { + throw new Error('Input data must be numbers') + } + // Zero in any number system is zero + if (number === 0) { + return '0' + } + let absoluteValue = Math.abs(number) + let convertedNumber = '' + while (absoluteValue > 0) { + // Every iteration last digit is taken away + // and added to the previous one + const lastDigit = absoluteValue % base + convertedNumber = lastDigit + convertedNumber + absoluteValue = Math.trunc(absoluteValue / base) + } + // Result is whether negative or positive, + // depending on the original value + if (number < 0) { + convertedNumber = '-' + convertedNumber + } + return convertedNumber +} + +export { intToBase } diff --git a/Maths/test/IntToBase.test.js b/Maths/test/IntToBase.test.js new file mode 100644 index 000000000..002dde6af --- /dev/null +++ b/Maths/test/IntToBase.test.js @@ -0,0 +1,25 @@ +import { intToBase } from '../intToBase' + +describe('Int to Base', () => { + test('Conversion to the binary system', () => { + expect(intToBase(210, 2)).toEqual('11010010') + expect(intToBase(-210, 2)).toEqual('-11010010') + }) + test('Conversion to the system with base 5', () => { + expect(intToBase(210, 5)).toEqual('1320') + expect(intToBase(-210, 5)).toEqual('-1320') + }) + test('Conversion to the octal system', () => { + expect(intToBase(210, 8)).toEqual('322') + expect(intToBase(-210, 8)).toEqual('-322') + }) + test('Output is 0', () => { + expect(intToBase(0, 8)).toEqual('0') + expect(intToBase(0, 8)).toEqual('0') + }) + test('Throwing an exception', () => { + expect(() => intToBase('string', 2)).toThrow() + expect(() => intToBase(10, 'base')).toThrow() + expect(() => intToBase(true, false)).toThrow() + }) +})