-
Notifications
You must be signed in to change notification settings - Fork 5
/
number.ts
47 lines (40 loc) · 1.26 KB
/
number.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { createFail, Runtype, setupInternalRuntype } from './runtype'
/**
* A number. By default reject NaN and Infinity values.
*
* Options:
*
* allowNaN .. allow NaN values
* allowInfinity .. allow positive and negative Infinity values
* min .. reject numbers smaller than that
* max .. reject numbers larger than that
*/
export function number(options?: {
allowNaN?: boolean
allowInfinity?: boolean
min?: number
max?: number
}): Runtype<number> {
const { allowNaN, allowInfinity, min, max } = options || {}
return setupInternalRuntype<number>(
(v, failOrThrow) => {
if (typeof v !== 'number') {
return createFail(failOrThrow, 'expected a number', v)
}
if (!allowNaN && isNaN(v)) {
return createFail(failOrThrow, 'expected a number that is not NaN', v)
}
if (!allowInfinity && (v === Infinity || v === -Infinity)) {
return createFail(failOrThrow, 'expected a finite number', v)
}
if (min !== undefined && v < min) {
return createFail(failOrThrow, `expected number to be >= ${min}`, v)
}
if (max !== undefined && v > max) {
return createFail(failOrThrow, `expected number to be <= ${max}`, v)
}
return v
},
{ isPure: true },
)
}