-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.js
54 lines (43 loc) · 1.22 KB
/
util.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
const unflatten = (flatObject) => {
const deepObject = {};
for (const key in flatObject) {
const value = flatObject[key];
const keys = key.split('.');
let currentObj = deepObject;
for (let i = 0; i < keys.length; i++) {
const currentKey = keys[i];
if (!currentObj[currentKey]) {
if (i === keys.length - 1) {
currentObj[currentKey] = value;
} else {
currentObj[currentKey] = {};
}
}
currentObj = currentObj[currentKey];
}
}
return deepObject;
}
const flatten = (deepObject) => {
const flatObject = {};
function flatten(obj, prefix = '') {
for (const key in obj) {
if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
flatten(obj[key], prefix + key + '.');
} else {
flatObject[prefix + key] = obj[key];
}
}
}
flatten(deepObject);
return flatObject;
}
const shuffle = (targets) => {
for (let i = targets.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[targets[i], targets[j]] = [targets[j], targets[i]];
};
};
module.exports = { flatten, unflatten, shuffle };
//console.log(flatten ({a:{b:{c:"aa"}}}));
//console.log(unflatten ({"a.b.c":"aa"}));