1
1
import type { Faker } from '.' ;
2
+ import { FakerError } from './errors/faker-error' ;
2
3
import { deprecated } from './internal/deprecated' ;
3
4
4
5
/**
@@ -24,7 +25,7 @@ export class Datatype {
24
25
* @param options.max Upper bound for generated number. Defaults to `min + 99999`.
25
26
* @param options.precision Precision of the generated number. Defaults to `1`.
26
27
*
27
- * @throws When options define `max < min`
28
+ * @throws When options define `max < min`.
28
29
*
29
30
* @example
30
31
* faker.datatype.number() // 55422
@@ -35,25 +36,25 @@ export class Datatype {
35
36
* faker.datatype.number({ min: 10, max: 100, precision: 0.01 }) // 36.94
36
37
*/
37
38
number (
38
- options ? : number | { min ?: number ; max ?: number ; precision ?: number }
39
+ options : number | { min ?: number ; max ?: number ; precision ?: number } = 99999
39
40
) : number {
40
- const opts = typeof options === 'number' ? { max : options } : options ?? { } ;
41
+ if ( typeof options === 'number' ) {
42
+ options = { max : options } ;
43
+ }
41
44
42
- const min = typeof opts . min === 'number' ? opts . min : 0 ;
43
- let max = typeof opts . max === 'number' ? opts . max : min + 99999 ;
44
- const precision = typeof opts . precision === 'number' ? opts . precision : 1 ;
45
+ const { min = 0 , precision = 1 } = options ;
46
+ const max = options . max ?? min + 99999 ;
45
47
46
- if ( max < min ) {
47
- throw new Error ( `Max ${ max } should be larger then min ${ min } ` ) ;
48
+ if ( max === min ) {
49
+ return min ;
48
50
}
49
51
50
- // Make the range inclusive of the max value
51
- if ( max >= 0 ) {
52
- max += precision ;
52
+ if ( max < min ) {
53
+ throw new FakerError ( `Max ${ max } should be larger then min ${ min } .` ) ;
53
54
}
54
55
55
56
const randomNumber = Math . floor (
56
- this . faker . mersenne . rand ( max / precision , min / precision )
57
+ this . faker . mersenne . rand ( max / precision + 1 , min / precision )
57
58
) ;
58
59
59
60
// Workaround problem in float point arithmetics for e.g. 6681493 / 0.01
0 commit comments