-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate_length.ts
83 lines (69 loc) · 1.82 KB
/
validate_length.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 { hasLength } from "./has_length.ts";
interface LengthValidate {
minimum: number;
maximum: number;
}
interface MinimumLengthValidate {
minimum: number;
}
interface MaximumLengthValidate {
maximum: number;
}
interface ExactLengthValidate {
is: number;
}
// deno-lint-ignore no-explicit-any
function isLengthValidate(options: any): options is LengthValidate {
return "minimum" in options || "maximum" in options;
}
function isMinimumLengthValidate(
// deno-lint-ignore no-explicit-any
options: any,
): options is MinimumLengthValidate {
const hasMinimum = "minimum" in options;
const hasMaximum = "maximum" in options;
return hasMinimum && !hasMaximum;
}
function isMaximumLengthValidate(
// deno-lint-ignore no-explicit-any
options: any,
): options is MaximumLengthValidate {
const hasMinimum = "minimum" in options;
const hasMaximum = "maximum" in options;
return !hasMinimum && hasMaximum;
}
// deno-lint-ignore no-explicit-any
function isExactLengthValidate(options: any): options is ExactLengthValidate {
return "is" in options;
}
export const validateLength = (
// deno-lint-ignore no-explicit-any
value: any,
options:
| LengthValidate
| MinimumLengthValidate
| MaximumLengthValidate
| ExactLengthValidate,
): boolean => {
if (!hasLength(value)) {
return false;
}
const length = value.length;
if (isExactLengthValidate(options)) {
return length === options.is;
}
if (isMinimumLengthValidate(options)) {
const { minimum } = options;
return minimum < length;
}
if (isMaximumLengthValidate(options)) {
const { maximum } = options;
return maximum > length;
}
if (isLengthValidate(options)) {
const length = value.length;
const { minimum, maximum } = options;
return minimum < length && maximum > length;
}
return false;
};