-
Notifications
You must be signed in to change notification settings - Fork 5
/
integer.ts
67 lines (58 loc) · 1.29 KB
/
integer.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import {
createFail,
InternalRuntype,
isFail,
propagateFail,
Runtype,
setupInternalRuntype,
} from './runtype'
export const integerRuntype = setupInternalRuntype<number>(
(v, failOrThrow) => {
if (typeof v === 'number' && Number.isSafeInteger(v)) {
return v
}
return createFail(failOrThrow, 'expected a safe integer', v)
},
{ isPure: true },
)
/**
* A Number that is a `isSafeInteger()`
*
* Options:
*
* min .. reject numbers smaller than that
* max .. reject number larger than that
*/
export function integer(options?: {
max?: number
min?: number
}): Runtype<number> {
if (!options) {
return integerRuntype
}
const { min, max } = options
return setupInternalRuntype<number>(
(v, failOrThrow) => {
const n = (integerRuntype as InternalRuntype<number>)(v, failOrThrow)
if (isFail(n)) {
return propagateFail(failOrThrow, n, v)
}
if (min !== undefined && n < min) {
return createFail(
failOrThrow,
`expected the integer to be >= ${min}`,
v,
)
}
if (max !== undefined && n > max) {
return createFail(
failOrThrow,
`expected the integer to be <= ${max}`,
v,
)
}
return n
},
{ isPure: true },
)
}