forked from diplodoc-platform/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
43 lines (36 loc) · 1.31 KB
/
utils.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
import evalExp from '@doc-tools/transform/lib/liquid/evaluation';
import {Filter} from '../models';
/**
* Filters file by expression and removes empty file's items.
* @param items
* @param itemsKey
* @param vars
* @return {T[]}
*/
export function filterFiles<T extends Filter>(items: T[], itemsKey: string, vars: Record<string, string>): T[] {
if (!Array.isArray(items)) {
const errorMessage
= `Error while filtering: item has invalid key '${itemsKey}' equals ${JSON.stringify(items)}`;
throw new Error(errorMessage);
}
return items.reduce((result: T[], item: T) => {
const {when} = item;
const whenResult = when === true || when === undefined || (typeof when === 'string' && evalExp(when, vars));
delete item.when;
if (whenResult) {
const property = item[itemsKey] as T[] | undefined;
if (property === undefined) {
result.push(item);
} else {
const filteredProperty = filterFiles(property, itemsKey, vars);
if (filteredProperty.length !== 0) {
result.push({
...item,
[itemsKey]: filteredProperty,
});
}
}
}
return result;
}, []);
}