Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions Maths/NumberOfDigits.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 }
13 changes: 12 additions & 1 deletion Maths/test/NumberOfDigits.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})
Loading