@coderich/util 0.0.3
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 +27 -0
- package/src/index.js +42 -0
package/package.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@coderich/util",
|
|
3
|
+
"main": "src/index.js",
|
|
4
|
+
"version": "0.0.3",
|
|
5
|
+
"publishConfig": {
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"files": [
|
|
9
|
+
"src",
|
|
10
|
+
"!__mocks__"
|
|
11
|
+
],
|
|
12
|
+
"scripts": {
|
|
13
|
+
"test": "jest --config=jest.config.js",
|
|
14
|
+
"lint": "eslint --config=.eslintrc ./",
|
|
15
|
+
"dev": "coderich-dev"
|
|
16
|
+
},
|
|
17
|
+
"devDependencies": {
|
|
18
|
+
"@coderich/dev": "0.0.13"
|
|
19
|
+
},
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git@github.com:CoderichLLC/nodejs-util.git"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"lodash.set": "4.3.2"
|
|
26
|
+
}
|
|
27
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
const ChildProcess = require('child_process');
|
|
2
|
+
const set = require('lodash.set');
|
|
3
|
+
|
|
4
|
+
exports.shellCommand = (cmd, ...args) => {
|
|
5
|
+
const { status = 0, stdout = '', stderr = '' } = ChildProcess.spawnSync(cmd, args.flat(), { shell: true, encoding: 'utf8' });
|
|
6
|
+
if (status !== 0) throw new Error(stderr);
|
|
7
|
+
return (stderr || stdout).trim();
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
exports.flatten = (mixed) => {
|
|
11
|
+
return exports.map(mixed, el => (function flatten(data, obj = {}, path = []) {
|
|
12
|
+
if (['[object Object]', '[object Array]'].includes(Object.prototype.toString.call(data))) {
|
|
13
|
+
return Object.entries(data).reduce((o, [key, value]) => {
|
|
14
|
+
const $key = key.split('.').length > 1 ? `['${key}']` : key;
|
|
15
|
+
return flatten(value, o, path.concat($key));
|
|
16
|
+
}, obj);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
if (path.length) {
|
|
20
|
+
obj[path.join('.')] = data;
|
|
21
|
+
return obj;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return data;
|
|
25
|
+
}(mixed)));
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
exports.unflatten = (data) => {
|
|
29
|
+
return exports.map(data, (el) => {
|
|
30
|
+
return typeof data === 'object' ? Object.entries(el).reduce((prev, [key, value]) => {
|
|
31
|
+
return set(prev, key, value);
|
|
32
|
+
}, {}) : el;
|
|
33
|
+
});
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
exports.map = (mixed, fn) => {
|
|
37
|
+
if (mixed == null) return mixed;
|
|
38
|
+
const isArray = Array.isArray(mixed);
|
|
39
|
+
const arr = isArray ? mixed : [mixed];
|
|
40
|
+
const results = arr.map((...args) => fn(...args));
|
|
41
|
+
return isArray ? results : results[0];
|
|
42
|
+
};
|