-
-
Notifications
You must be signed in to change notification settings - Fork 629
/
utils.js
98 lines (81 loc) · 2.39 KB
/
utils.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
export function makeString(object) {
if (object == null) return '';
/* eslint prefer-template: 0 */
return '' + object;
}
export function copy(a, s, t) {
a.forEach((m) => {
if (s[m]) t[m] = s[m];
});
}
function getLastOfPath(object, path, Empty) {
function cleanKey(key) {
return (key && key.indexOf('###') > -1) ? key.replace(/###/g, '.') : key;
}
function canNotTraverseDeeper() {
return !object || typeof object === 'string';
}
const stack = (typeof path !== 'string') ? [].concat(path) : path.split('.');
while (stack.length > 1) {
if (canNotTraverseDeeper()) return {};
const key = cleanKey(stack.shift());
if (!object[key] && Empty) object[key] = new Empty();
object = object[key];
}
if (canNotTraverseDeeper()) return {};
return {
obj: object,
k: cleanKey(stack.shift())
};
}
export function setPath(object, path, newValue) {
const { obj, k } = getLastOfPath(object, path, Object);
obj[k] = newValue;
}
export function pushPath(object, path, newValue, concat) {
const { obj, k } = getLastOfPath(object, path, Object);
obj[k] = obj[k] || [];
if (concat) obj[k] = obj[k].concat(newValue);
if (!concat) obj[k].push(newValue);
}
export function getPath(object, path) {
const { obj, k } = getLastOfPath(object, path);
if (!obj) return undefined;
return obj[k];
}
export function deepExtend(target, source, overwrite) {
/* eslint no-restricted-syntax: 0 */
for (const prop in source) {
if (prop in target) {
// If we reached a leaf string in target or source then replace with source or skip depending on the 'overwrite' switch
if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) {
if (overwrite) target[prop] = source[prop];
} else {
deepExtend(target[prop], source[prop], overwrite);
}
} else {
target[prop] = source[prop];
}
}
return target;
}
export function regexEscape(str) {
/* eslint no-useless-escape: 0 */
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
/* eslint-disable */
var _entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
/* eslint-enable */
export function escape(data) {
if (typeof data === 'string') {
return data.replace(/[&<>"'\/]/g, s => _entityMap[s]);
}
return data;
}