-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
50 lines (43 loc) · 1.06 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
import { OF_UNDEFINED } from '../../constants';
import { isBoolean } from '../../filters/isBoolean';
import { FallbackHandler } from '../../types/FallbackHandler';
export interface ToBooleanOptions {
/**
* Values that should be treated as boolean false.
* @default [ 'false' ]
*/
falseValues?: any[];
/**
* Values that should be treated as boolean true.
* @default [ 'true' ]
*/
trueValues?: any[];
/**
* Action to perform when value can't be mapped into a boolean.
* Returns undefined by default.
* Throws `TypeError` if manually unset.
*/
onFallback?: FallbackHandler;
}
/**
* Maps value into a boolean if possible.
*/
export const toBoolean = (
value: unknown,
{
falseValues = ['false'],
trueValues = ['true'],
onFallback = OF_UNDEFINED,
}: ToBooleanOptions = {}
): boolean => {
if (isBoolean(value)) {
return value;
}
if (falseValues.length && falseValues.includes(value)) {
return false;
}
if (trueValues.length && trueValues.includes(value)) {
return true;
}
return onFallback(value);
};