-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilter-callable.ts
50 lines (46 loc) · 1.25 KB
/
filter-callable.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
/**
* @typedef {import("../types.js").AttrValueFilter} AttrValueFilter
*/
import type {
AttrName,
AttrValue,
AttrValueFilter,
AttrValueFilterFallback,
} from '../types.js';
/**
* Creates a filter function that applies the given filter to a given value or
* it's returned result if the value is a function.
*
* @param {AttrValueFilter} filter
* @throws {TypeError} If the filter is not a function.
* @returns {AttrValueFilter}
*/
export function createFilterCallable(
filter: AttrValueFilter
): AttrValueFilter {
if (typeof filter !== 'function') {
throw new TypeError(
`createFilterCallable expected the filter to be a function`
);
}
/**
* Filters the result of the value if it is a function,
* otherwise the value itself.
*
* The fallback argument is left undefined to allow the inner
* filter function to use its own default value.
*
* @type {AttrValueFilter}
*/
function filterCallable(
value: unknown,
name?: AttrName,
fallback?: AttrValueFilterFallback
): AttrValue {
if (typeof value === 'function') {
value = value();
}
return filter(value, name, fallback);
}
return filterCallable;
}