File tree Expand file tree Collapse file tree 2 files changed +21
-2
lines changed Expand file tree Collapse file tree 2 files changed +21
-2
lines changed Original file line number Diff line number Diff line change 99
1010const numberOfDigit = ( n ) => Math . abs ( n ) . toString ( ) . length
1111
12- export { numberOfDigit }
12+ /**
13+ * Returns the number of digits of a given integer.
14+ *
15+ * @param {number } n - The integer for which to count digits.
16+ * @returns {number } The number of digits in the integer.
17+ * @see https://math.stackexchange.com/questions/2145480/how-does-the-logarithm-returns-the-number-of-digits-of-a-number
18+ * @author dev-madhurendra
19+ */
20+ const numberOfDigitsUsingLog = ( n ) => n === 0 ? 1 : Math . floor ( Math . log10 ( Math . abs ( n ) ) ) + 1
21+
22+ export { numberOfDigit , numberOfDigitsUsingLog }
Original file line number Diff line number Diff line change 1- import { numberOfDigit } from '../NumberOfDigits'
1+ import { numberOfDigit , numberOfDigitsUsingLog } from '../NumberOfDigits'
22
33describe ( 'NumberOfDigits' , ( ) => {
44 it ( 'should return the correct number of digits for an integer' , ( ) => {
@@ -8,4 +8,13 @@ describe('NumberOfDigits', () => {
88 it ( 'should return the correct number of digits for a negative number' , ( ) => {
99 expect ( numberOfDigit ( - 2346243 ) ) . toBe ( 7 )
1010 } )
11+
12+ it . each ( [
13+ [ 0 , 1 ] ,
14+ [ 123423232 , 9 ] ,
15+ [ - 123423232 , 9 ] ,
16+ [ 9999 , 4 ]
17+ ] ) ( 'should return the correct number of digits in an integer' , ( value , expected ) => {
18+ expect ( numberOfDigitsUsingLog ( value ) ) . toBe ( expected )
19+ } )
1120} )
You can’t perform that action at this time.
0 commit comments