@coderich/util 0.1.6 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/index.js +12 -7
package/package.json
CHANGED
package/src/index.js
CHANGED
|
@@ -16,6 +16,13 @@ exports.filterBy = (arr, fn) => arr.filter((b, index) => index === arr.findIndex
|
|
|
16
16
|
exports.ensureArray = a => (Array.isArray(a) ? a : [a].filter(el => el !== undefined));
|
|
17
17
|
exports.timeout = ms => new Promise((resolve) => { setTimeout(resolve, ms); });
|
|
18
18
|
exports.ucFirst = string => string.charAt(0).toUpperCase() + string.slice(1);
|
|
19
|
+
exports.isPlainArrayOrObject = obj => Array.isArray(obj) || exports.isPlainObject(obj);
|
|
20
|
+
|
|
21
|
+
exports.isPlainObject = (obj) => {
|
|
22
|
+
if (obj == null) return false;
|
|
23
|
+
const proto = Object.getPrototypeOf(obj);
|
|
24
|
+
return proto === Object.prototype || proto.toString?.call?.(obj) === '[object Object]';
|
|
25
|
+
};
|
|
19
26
|
|
|
20
27
|
exports.filterRe = (arr, fn) => {
|
|
21
28
|
const map = new Map();
|
|
@@ -35,12 +42,10 @@ exports.shellCommand = (cmd, ...args) => {
|
|
|
35
42
|
|
|
36
43
|
exports.flatten = (mixed, options = {}) => {
|
|
37
44
|
const maxDepth = options.depth ?? Infinity;
|
|
45
|
+
const typeFn = options.safe ? exports.isPlainObject : exports.isPlainArrayOrObject;
|
|
38
46
|
|
|
39
47
|
return exports.map(mixed, el => (function flatten(data, obj = {}, path = [], depth = 0) {
|
|
40
|
-
|
|
41
|
-
const types = options.safe ? ['[object Object]'] : ['[object Object]', '[object Array]'];
|
|
42
|
-
|
|
43
|
-
if (depth <= maxDepth && types.includes(type) && Object.keys(data).length && !ObjectId.isValid(data)) {
|
|
48
|
+
if (depth <= maxDepth && Object.keys(data).length && typeFn(data)) {
|
|
44
49
|
return Object.entries(data).reduce((o, [key, value]) => {
|
|
45
50
|
const $key = options.strict && key.split('.').length > 1 ? `['${key}']` : key;
|
|
46
51
|
return flatten(value, o, path.concat($key), depth + 1);
|
|
@@ -57,10 +62,10 @@ exports.flatten = (mixed, options = {}) => {
|
|
|
57
62
|
};
|
|
58
63
|
|
|
59
64
|
exports.unflatten = (data, options = {}) => {
|
|
65
|
+
const typeFn = options.safe ? exports.isPlainObject : exports.isPlainArrayOrObject;
|
|
66
|
+
|
|
60
67
|
return exports.map(data, (el) => {
|
|
61
|
-
|
|
62
|
-
const types = options.safe ? ['[object Object]'] : ['[object Object]', '[object Array]'];
|
|
63
|
-
return types.includes(type) ? Object.entries(el).reduce((prev, [key, value]) => {
|
|
68
|
+
return typeFn(data) ? Object.entries(el).reduce((prev, [key, value]) => {
|
|
64
69
|
return set(prev, key, value);
|
|
65
70
|
}, {}) : el;
|
|
66
71
|
});
|