-
Notifications
You must be signed in to change notification settings - Fork 46
/
arrays-objects-helpers.js
122 lines (110 loc) · 2.28 KB
/
arrays-objects-helpers.js
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
function _isObject(obj) {
return obj === Object(obj);
}
// EXAMPLE INPUT:
// {
// foo: {
// name: "foo!"
// },
// bar: {
// name: "bar"
// }
// }
//
// EXAMPLE OUTPUT:
// [ { name: "foo!", key: "foo" }, { name: "bar", key: "bar" } ]
function _objectToArray(obj) {
if (Array.isArray(obj)) {
return obj;
}
return Object.keys(obj).map(key => {
if (_isObject(obj[key])) {
obj[key].key = key;
}
return obj[key];
});
}
// EXAMPLE INPUT:
// [
// { foo: { ... } },
// { bar: { ... } },
// ]
//
// EXAMPLE OUTPUT:
// { foo: { orderHint: 0, ... }, bar: { orderHint: 1, ... } }
function _arrayToObject(arr) {
return arr.reduce((acc, cur, idx) => {
Object.keys(cur).forEach(key => {
acc[key] = cur[key];
acc[key].orderHint = idx;
});
return acc;
}, {});
}
// PUBLIC
function recursiveObjectToArray(obj) {
if (_isObject(obj)) {
Object.keys(obj).forEach(key => {
const value = obj[key];
if (
_isObject(obj) &&
[
'responses',
'body',
'queryParameters',
'headers',
'properties',
'baseUriParameters',
'annotations',
'uriParameters',
].indexOf(key) !== -1
) {
obj[key] = _objectToArray(value);
}
recursiveObjectToArray(value);
});
} else if (Array.isArray(obj)) {
obj.forEach(value => {
recursiveObjectToArray(value);
});
}
return obj;
}
// Transform some TOP LEVEL properties from objects to simple arrays
function objectsToArrays(ramlObj) {
[
'types',
'traits',
'resourceTypes',
'annotationTypes',
'securitySchemes',
].forEach(key => {
if (ramlObj[key]) {
ramlObj[key] = _objectToArray(ramlObj[key]);
ramlObj[key].sort((first, second) => {
first.orderHint - second.orderHint;
});
}
});
return ramlObj;
}
// Transform some TOP LEVEL properties from arrays to simple objects
function arraysToObjects(ramlObj) {
[
'types',
'traits',
'resourceTypes',
'annotationTypes',
'securitySchemes',
].forEach(key => {
if (ramlObj[key]) {
ramlObj[key] = _arrayToObject(ramlObj[key]);
}
});
return ramlObj;
}
module.exports = {
arraysToObjects,
recursiveObjectToArray,
objectsToArrays,
};