-
Notifications
You must be signed in to change notification settings - Fork 5
/
array.ts
83 lines (70 loc) · 1.89 KB
/
array.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import {
createFail,
failSymbol,
getInternalRuntype,
InternalRuntype,
isFail,
propagateFail,
Runtype,
setupInternalRuntype,
} from './runtype'
export const arrayRuntype: InternalRuntype<unknown[]> = (v, failOrThrow) => {
if (Array.isArray(v)) {
return v
}
return createFail(failOrThrow, `expected an Array`, v)
}
/**
* An array of a given type.
*
* Options:
*
* minLength .. reject arrays shorter than that
* maxLength .. reject arrays longer than that
*/
export function array<A>(
a: Runtype<A>,
options?: { maxLength?: number; minLength?: number },
): Runtype<A[]> {
const { maxLength, minLength } = options || {}
const internalA = getInternalRuntype(a)
const isPure = !!internalA.meta?.isPure
return setupInternalRuntype<A[]>(
(v, failOrThrow) => {
const arrayValue = arrayRuntype(v, failOrThrow)
if (isFail(arrayValue)) {
return propagateFail(failOrThrow, arrayValue, v)
}
if (maxLength !== undefined && arrayValue.length > maxLength) {
return createFail(
failOrThrow,
`expected the array to contain at most ${maxLength} elements`,
v,
)
}
if (minLength !== undefined && arrayValue.length < minLength) {
return createFail(
failOrThrow,
`expected the array to contain at least ${minLength} elements`,
v,
)
}
// copy the unknown array in case the item runtype is not pure (we do not
// mutate anything in place)
const res: A[] = isPure ? arrayValue : new Array(arrayValue.length)
for (let i = 0; i < arrayValue.length; i++) {
const item = internalA(arrayValue[i], failSymbol)
if (isFail(item)) {
return propagateFail(failOrThrow, item, v, i)
}
if (!isPure) {
res[i] = item
}
}
return res
},
{
isPure,
},
)
}