-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
52 lines (50 loc) · 1.58 KB
/
index.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
import Guard from "../../Guard";
import TValidate from "../TValidate";
/**
* Validates an array of elements.
*
* `guard.name: "<type>[](minLength:<minLength>,maxLength:<maxLength>)"`
*
* @returns
* A `Guard` that checks if the given value is an array of the given type.
*
* @param guard - The guard, which validates the elements of the array.
* @param options.minLength - The array must be at least this long.
* @param options.maxLength - The array can't be longer than this.
*
* @example
* ```ts
* const TNumbers = TArray(TNumber);
* TNumbers.isValid([1, 2, 3]); // true
* TNumbers.isValid([1, 2, "3"]); // false
* TNumbers.name === "number[]"; // true
* ```
*/
export default function TArray<T>(
guard: Guard<T>,
options?: { minLength?: number; maxLength?: number }
): Guard<Array<T>> {
const isOptionEmpty =
options?.minLength === undefined && options?.maxLength === undefined;
let name = `${guard.name}[]`;
if (!isOptionEmpty) name += "(";
if (options?.minLength !== undefined)
name += `minLength=${options.minLength}`;
if (options?.minLength !== undefined && options.maxLength !== undefined)
name += ",";
if (options?.maxLength !== undefined)
name += `maxLength=${options.maxLength}`;
if (!isOptionEmpty) name += ")";
return TValidate<Array<T>>(name, (value) => {
if (!Array.isArray(value)) return false;
if (
(options?.minLength || 0) > value.length ||
(options?.maxLength || Infinity) < value.length
)
return false;
for (const item of value) {
if (!guard.isValid(item)) return false;
}
return true;
});
}