-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
93 lines (75 loc) · 2.38 KB
/
index.js
File metadata and controls
93 lines (75 loc) · 2.38 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
86
87
88
89
90
91
92
93
const { propToPath, isPrimitive } = require("./utils");
function set(defaultObject, prop, value) {
const paths = propToPath(prop);
function setPropertyValue(object, index) {
let clone = Object.assign({}, object);
if (paths.length > index) {
if (Array.isArray(object)) {
paths[index] = parseInt(paths[index]);
clone = object.slice();
}
clone[paths[index]] = setPropertyValue(object[paths[index]], index + 1);
return clone;
}
return value;
}
return setPropertyValue(defaultObject, 0);
}
function del(defaultObject, prop) {
const paths = propToPath(prop);
function deletePropertyValue(object, index) {
let clone = Object.assign({}, object);
if (paths.length > index) {
if (Array.isArray(object)) {
paths[index] = parseInt(paths[index]);
clone = object.slice();
clone.splice(paths[index], 1);
return clone;
}
const result = deletePropertyValue(object[paths[index]], index + 1);
typeof result === "undefined"
? delete clone[paths[index]]
: (clone[paths[index]] = result);
return clone;
}
return undefined;
}
return deletePropertyValue(defaultObject, 0);
}
function get(defaultObject, prop) {
const paths = propToPath(prop);
function getPropertyValue(object, index) {
const clone = Object.assign({}, object);
if (paths.length === index + 1) {
if (Array.isArray(clone[paths[index]])) {
return clone[paths[index]].slice();
} else if (typeof clone[paths[index]] === "object") {
return Object.assign({}, clone[paths[index]]);
}
return clone[paths[index]];
}
return getPropertyValue(object[paths[index]], index + 1);
}
return getPropertyValue(defaultObject, 0);
}
function merge(defaultObject, prop, value) {
const targetValue = get(defaultObject, prop);
if (typeof targetValue === "undefined" || isPrimitive(value)) {
throw new Error("Target value is undefine, verify your property path");
}
if (Array.isArray(value)) {
if (!Array.isArray(targetValue)) {
throw new Error("The bot values should be arrays");
}
const resultValue = targetValue.concat(value);
return set(defaultObject, prop, resultValue);
}
const resultValue = Object.assign(targetValue, value);
return set(defaultObject, prop, resultValue);
}
module.exports = {
set,
del,
get,
merge,
};