-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.js
58 lines (52 loc) · 1.83 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
/**
* Performs forEach async callback on an array in serial manner.
* @param {Array} array - Array or array-like object over which to iterate.
* @param {function} callback - The function to call, wait await, for every element.
*/
exports.asyncForEach = async (array, callback) => {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
};
/**
* Performs map callback on an array in async manner.
* @param {Array} m - Array or array-like object over which to iterate.
* @param {function} callback - The function to call, wait await, for every element.
*/
exports.asyncMapForEach = async (m, callback) => {
for (const e of m.entries()) {
await callback(e[1], e[0]);
}
};
const isPlainObj = (o) => Boolean(
o && o.constructor && o.constructor.prototype &&
o.constructor.prototype.hasOwnProperty('isPrototypeOf'),
);
const flatten = (obj, keys = []) => {
return Object.keys(obj).reduce((acc, key) => {
return Object.assign(acc,
isPlainObj(obj[key]) ? flatten(obj[key], keys.concat(key)) : {
[keys.concat(key).join('.')]: obj[key],
});
}, {});
};
exports.flatten = flatten;
exports.filterNulls = (obj) => {
const sets = {};
const unSets = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key] === null) {
unSets[key] = '';
} else {
sets[key] = obj[key];
}
}
}
return [sets, unSets];
};
// eslint-disable-next-line no-extend-native
String.prototype.formatStr = function formatStr(...args) {
const params = arguments.length === 1 && typeof args[0] === 'object' ? args[0] : args;
return this.replace(/\{([^}]+)\}/g, (match, key) => (typeof params[key] !== 'undefined' ? params[key] : match));
};