-
Notifications
You must be signed in to change notification settings - Fork 7
/
utils.js
58 lines (52 loc) · 1.57 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
function randomName() {
return `Z-${Math.floor(Math.random() * 100000000) + 1}`;
}
function isFunction(func) {
return func && typeof func === 'function';
}
function arraysIntersection(...arrays) {
const verifiedArrays = arrays.filter((value) => Array.isArray(value));
if (arrays.length === 0) return arrays;
return verifiedArrays.reduce((acc, currentArray) => {
currentArray.forEach((currentValue) => {
if (acc.indexOf(currentValue) === -1) {
if (verifiedArrays.filter((obj) => obj.indexOf(currentValue) === -1).length === 0) {
acc.push(currentValue);
}
}
});
return acc;
}, []);
}
function hasProp(obj, key) {
if (obj.hasOwnProperty(key)) return true; // Some properties with '.' could fail, so we do a quick check
const keyParts = key.split('.');
return (
!!obj &&
(keyParts.length > 1 ? hasProp(obj[key.split('.')[0]], keyParts.slice(1).join('.')) : obj.hasOwnProperty(key))
);
}
function getProp(obj, key) {
if (!!obj && obj.hasOwnProperty(key)) return obj[key]; // Some properties with '.' could fail, so we do a quick check
if (key.includes('.')) {
const keyParts = key.split('.');
return getProp(obj[keyParts[0]], keyParts.slice(1).join('.'));
}
}
function setProp(obj, key, value) {
if (!key.includes('.')) {
obj[key] = value;
return;
}
const keyParts = key.split('.');
if (!obj[keyParts[0]]) obj[keyParts[0]] = {};
setProp(obj[keyParts[0]], keyParts.slice(1).join('.'), value);
}
module.exports = {
randomName,
isFunction,
arraysIntersection,
hasProp,
getProp,
setProp,
};