This repository has been archived by the owner on Dec 19, 2023. It is now read-only.
forked from saga7878/safe-object
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
65 lines (56 loc) · 1.63 KB
/
index.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
function isArray(ary) {
return Object.prototype.toString.call(ary).slice(8, -1) === "Array";
}
function safeObject2(objs) {
if (!new.target) return new safeObject2(objs);
this.objs = objs;
}
safeObject2.prototype.getter = function(prop, def = "") {
if (prop == null || !prop) return "";
const isAry = isArray(prop);
let value;
if (isAry) {
let idx = 0;
value = this.objs;
while (idx < prop.length) {
if (value == null) return def;
let x = prop[idx];
value = value[x];
idx++;
}
} else {
value = Reflect.get(this.objs, prop);
}
return value === undefined || value == null || value !== value
? def
: value;
};
safeObject2.prototype.setter = function(paths, value) {
if (paths.includes('__proto__') || paths.includes('constructor') || paths.includes('prototype')) {
return false;
}
if (paths == null || !paths) return this.objs;
let curValue,
idx = 0;
const props = [];
paths.reduce((init, acc) => {
props.push(acc);
curValue = this.getter(props);
if (typeof curValue !== "object") {
console.log(paths[idx + 1]);
curValue =
Number.isInteger(props[props.length - 1]) ||
Number.isInteger(paths[idx + 1])
? []
: {};
}
if (acc === paths[paths.length - 1]) {
curValue = value;
}
init[acc] = curValue;
idx++;
return init[acc];
}, this.objs);
return this.objs;
};
module.exports = safeObject2;