-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathconditions-mapper.js
More file actions
85 lines (73 loc) · 1.88 KB
/
Copy pathconditions-mapper.js
File metadata and controls
85 lines (73 loc) · 1.88 KB
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
84
85
/*
conditionsMapper will remap a conditions object and create an object with each depending fieldName as a key.
Since one field can be involed in more than one condition, an array of condition references will be created under each fieldName key
Since more than one field can be involved in the same condition, the same condition might be referenced from
several condition arrays.
*/
function isObject(obj) {
return obj !== null && typeof obj === 'object' && !Array.isArray(obj);
}
function isArray(obj) {
return Array.isArray(obj);
}
export const conditionsMapper = ({conditions}) => {
if (!conditions) return {};
function traverse({obj, fnc, key}) {
fnc && fnc({obj, key});
if (isArray(obj)) {
traverseArray({
obj,
fnc,
key,
});
} else if (isObject(obj)) {
traverseObject({
obj,
fnc,
key,
});
}
}
function traverseArray({obj, fnc, key}) {
obj.forEach(([key, item]) => {
traverse({
obj: item,
fnc,
key,
});
});
}
function traverseObject({obj, fnc, key}) {
Object.entries(obj).forEach(([key, item]) => {
traverse({
obj: item,
fnc,
key,
});
});
}
const indexedConditions = {};
const conditionArray = Object.entries(conditions);
conditionArray
.map(([key, condition]) => {
return {
key: key,
...condition,
};
})
.forEach(condition => {
traverse({
obj: condition,
fnc: ({obj, key}) => {
if (key === 'when') {
const fieldNames = isArray(obj) ? obj : [obj];
fieldNames.map(fieldName => {
indexedConditions[fieldName] = indexedConditions[fieldName] || [];
indexedConditions[fieldName].push(condition);
});
}
},
});
});
return indexedConditions;
};