diff --git a/Maths/NumberOfDigits.js b/Maths/NumberOfDigits.js index 8a3e2b3c6a..7207ce9b94 100644 --- a/Maths/NumberOfDigits.js +++ b/Maths/NumberOfDigits.js @@ -7,7 +7,12 @@ * */ -const numberOfDigit = (n) => Math.abs(n).toString().length +const numberOfDigit = (n) => { + if (typeof n !== 'number' || !Number.isFinite(n)) { + throw new TypeError('Input must be a finite number') + } + return Math.abs(Math.trunc(n)).toString().length +} /** * Returns the number of digits of a given integer. @@ -17,7 +22,20 @@ const numberOfDigit = (n) => Math.abs(n).toString().length * @see https://math.stackexchange.com/questions/2145480/how-does-the-logarithm-returns-the-number-of-digits-of-a-number * @author dev-madhurendra */ -const numberOfDigitsUsingLog = (n) => - n === 0 ? 1 : Math.floor(Math.log10(Math.abs(n))) + 1 +const numberOfDigitsUsingLog = (n) => { + if (typeof n !== 'number' || !Number.isFinite(n)) { + throw new TypeError('Input must be a finite number') + } + const intVal = Math.trunc(n) + if (intVal === 0) return 1 + const abs = Math.abs(intVal) + let digits = Math.floor(Math.log10(abs)) + 1 + if (Math.pow(10, digits - 1) > abs) { + digits-- + } else if (Math.pow(10, digits) <= abs) { + digits++ + } + return digits +} export { numberOfDigit, numberOfDigitsUsingLog } diff --git a/Maths/test/NumberOfDigits.test.js b/Maths/test/NumberOfDigits.test.js index e3495eb9ea..6a78b3d30b 100644 --- a/Maths/test/NumberOfDigits.test.js +++ b/Maths/test/NumberOfDigits.test.js @@ -13,11 +13,22 @@ describe('NumberOfDigits', () => { [0, 1], [123423232, 9], [-123423232, 9], - [9999, 4] + [9999, 4], + [999999999999999, 15], + [1000000000000000, 16], + [1000000000000001, 16] ])( 'should return the correct number of digits in an integer', (value, expected) => { expect(numberOfDigitsUsingLog(value)).toBe(expected) + expect(numberOfDigit(value)).toBe(expected) } ) + + it('should throw TypeError for invalid inputs', () => { + expect(() => numberOfDigit('123')).toThrow(TypeError) + expect(() => numberOfDigit(NaN)).toThrow(TypeError) + expect(() => numberOfDigitsUsingLog('123')).toThrow(TypeError) + expect(() => numberOfDigitsUsingLog(NaN)).toThrow(TypeError) + }) })