-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
guard.ts
55 lines (53 loc) · 1.27 KB
/
guard.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
export class Guard {
/**
* Checks if value is empty. Accepts strings, numbers, booleans, objects and arrays.
*/
static isEmpty(value: unknown): boolean {
if (typeof value === 'number' || typeof value === 'boolean') {
return false;
}
if (typeof value === 'undefined' || value === null) {
return true;
}
if (value instanceof Date) {
return false;
}
if (value instanceof Object && !Object.keys(value).length) {
return true;
}
if (Array.isArray(value)) {
if (value.length === 0) {
return true;
}
if (value.every((item) => Guard.isEmpty(item))) {
return true;
}
}
if (value === '') {
return true;
}
return false;
}
/**
* Checks length range of a provided number/string/array
*/
static lengthIsBetween(
value: number | string | Array<unknown>,
min: number,
max: number,
): boolean {
if (Guard.isEmpty(value)) {
throw new Error(
'Cannot check length of a value. Provided value is empty',
);
}
const valueLength =
typeof value === 'number'
? Number(value).toString().length
: value.length;
if (valueLength >= min && valueLength <= max) {
return true;
}
return false;
}
}