@wxhccc/es-util 2.0.1 → 2.1.0
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/README.md +76 -0
- package/dist/array-tree-switch.d.ts +30 -1
- package/dist/array-tree-switch.js +132 -0
- package/dist/event-target-emitter.js +1 -1
- package/dist/index.esm.js +57 -5
- package/dist/index.js +57 -4
- package/dist/index.min.js +2 -2
- package/dist/object-array.js +1 -1
- package/dist/optional.js +1 -1
- package/dist/page-communicate.js +2 -2
- package/dist/promise.d.ts +10 -9
- package/dist/promise.js +4 -3
- package/dist/raf-timer.js +1 -1
- package/dist/types.d.ts +1 -0
- package/dist/utils.js +1 -1
- package/dist/validate.js +1 -1
- package/dist/value-string-switch.js +1 -1
- package/package.json +6 -2
package/README.md
CHANGED
|
@@ -218,6 +218,82 @@ console.log(tree)
|
|
|
218
218
|
*/
|
|
219
219
|
```
|
|
220
220
|
|
|
221
|
+
### `treeAnalyse(tree, options, keys)`
|
|
222
|
+
|
|
223
|
+
> v2.1.0 add
|
|
224
|
+
|
|
225
|
+
analyse tree data, return an object contain typed handled data
|
|
226
|
+
|
|
227
|
+
**parameters:**
|
|
228
|
+
- **tree** {TreeNode[] | object} The tree structure need to transform.
|
|
229
|
+
- **options** {object} The options.
|
|
230
|
+
- **primaryKey** {string} the primary key of node item, default `'id'`
|
|
231
|
+
- **labelKey** {string} the primary key of node item, default `'name'`
|
|
232
|
+
- **disabledKey** {string} the disabled key of node item, default `'disabled'`
|
|
233
|
+
- **childrenKey** {string} the childrenKey key of node item, default `'children'`
|
|
234
|
+
- **keys** {('nodes' | 'keyNodeMap' | 'childKeysMaps' | 'disabledKeys')[]} the modules need to handle
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
**returns**: AnalyseTreeData
|
|
238
|
+
|
|
239
|
+
Example
|
|
240
|
+
|
|
241
|
+
```javascript
|
|
242
|
+
import { treeAnalyse } from '@wxhccc/es-util'
|
|
243
|
+
|
|
244
|
+
const tree = [
|
|
245
|
+
{
|
|
246
|
+
id: 1,
|
|
247
|
+
name: 'language',
|
|
248
|
+
children: [
|
|
249
|
+
{
|
|
250
|
+
id: 2,
|
|
251
|
+
name: 'english',
|
|
252
|
+
children: []
|
|
253
|
+
},
|
|
254
|
+
{
|
|
255
|
+
id: 3,
|
|
256
|
+
name: 'chinese',
|
|
257
|
+
children: []
|
|
258
|
+
}
|
|
259
|
+
]
|
|
260
|
+
}
|
|
261
|
+
]
|
|
262
|
+
|
|
263
|
+
const result = array2tree(array)
|
|
264
|
+
console.log(result)
|
|
265
|
+
/* log
|
|
266
|
+
{
|
|
267
|
+
"nodes": [
|
|
268
|
+
{
|
|
269
|
+
"id": 1,
|
|
270
|
+
"name": "language",
|
|
271
|
+
"children": [{…}, {…}]
|
|
272
|
+
},
|
|
273
|
+
{
|
|
274
|
+
"id": 2,
|
|
275
|
+
"name": "english",
|
|
276
|
+
"children": []
|
|
277
|
+
},
|
|
278
|
+
{
|
|
279
|
+
"id": 3,
|
|
280
|
+
"name": "chinese",
|
|
281
|
+
"children": []
|
|
282
|
+
}
|
|
283
|
+
],
|
|
284
|
+
"childKeysMaps": {
|
|
285
|
+
"1": [2, 3]
|
|
286
|
+
},
|
|
287
|
+
"keyNodeMap": {
|
|
288
|
+
1: {keyVlaue: 1, keyLabel: 'language', parent: undefined, children: [{…}, {…}]},
|
|
289
|
+
2: {keyVlaue: 2, keyLabel: 'english', parent: {…}, children: [] },
|
|
290
|
+
3: {keyVlaue: 3, keyLabel: 'chinese', parent: {…}, children: [] }
|
|
291
|
+
},
|
|
292
|
+
"disabledKeys": []
|
|
293
|
+
}
|
|
294
|
+
*/
|
|
295
|
+
```
|
|
296
|
+
|
|
221
297
|
## validate module
|
|
222
298
|
|
|
223
299
|
### `ChinaIdCardValid(idCard)`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AnyFunction } from './types';
|
|
1
|
+
import { AnyFunction, StrOrNum } from './types';
|
|
2
2
|
export interface Node {
|
|
3
3
|
[key: string]: any;
|
|
4
4
|
}
|
|
@@ -6,8 +6,13 @@ export interface TreeNode {
|
|
|
6
6
|
[key: string]: any;
|
|
7
7
|
}
|
|
8
8
|
interface Options {
|
|
9
|
+
/** 主键key */
|
|
9
10
|
primaryKey?: string;
|
|
11
|
+
/** 文字key */
|
|
12
|
+
labelKey?: string;
|
|
13
|
+
/** 父元素key */
|
|
10
14
|
parentKey?: string;
|
|
15
|
+
/** 子元素集合key */
|
|
11
16
|
childrenKey?: string;
|
|
12
17
|
}
|
|
13
18
|
interface TreeOptions extends Options {
|
|
@@ -62,4 +67,28 @@ export declare function tree2array(tree: Tree, options?: NodeOptions & {
|
|
|
62
67
|
export declare function tree2array(tree: Tree, options: NodeOptions & {
|
|
63
68
|
returnObject: true;
|
|
64
69
|
}): NodeMap;
|
|
70
|
+
export interface TreeKeyNode {
|
|
71
|
+
keyVlaue: StrOrNum;
|
|
72
|
+
keyLabel?: StrOrNum;
|
|
73
|
+
parent?: TreeKeyNode;
|
|
74
|
+
children: TreeKeyNode[];
|
|
75
|
+
}
|
|
76
|
+
export interface AnalyseTreeData<T extends TreeNode = TreeNode> {
|
|
77
|
+
nodes: T[];
|
|
78
|
+
childKeysMaps: Record<StrOrNum, StrOrNum[]>;
|
|
79
|
+
keyNodeMap: Record<string, TreeKeyNode>;
|
|
80
|
+
disabledKeys: StrOrNum[];
|
|
81
|
+
}
|
|
82
|
+
declare type AnalyseTreeModule = keyof AnalyseTreeData;
|
|
83
|
+
interface TreeAnalyseOptions extends Omit<Options, 'parentKey'> {
|
|
84
|
+
disabledKey?: string;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* 分析id唯一的树节点,得到不同结构的数据
|
|
88
|
+
* @param treeData 树数据
|
|
89
|
+
* @param options 配置项
|
|
90
|
+
* @param keys 可指定的数据类型的key,默认返回完整数据
|
|
91
|
+
* @returns
|
|
92
|
+
*/
|
|
93
|
+
export declare function treeAnalyse<T extends TreeNode = TreeNode>(treeData: T[], options?: TreeAnalyseOptions, keys?: AnalyseTreeModule[]): AnalyseTreeData<T>;
|
|
65
94
|
export {};
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* @wxhccc/es-util v2.1.0
|
|
3
|
+
* (c) 2022 wxhccc
|
|
4
|
+
* @license MIT
|
|
5
|
+
*/
|
|
6
|
+
'use strict';
|
|
7
|
+
|
|
8
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
9
|
+
|
|
10
|
+
var utils = require('./utils.js');
|
|
11
|
+
|
|
12
|
+
function createNode(children, value = []) {
|
|
13
|
+
return { [children]: value };
|
|
14
|
+
}
|
|
15
|
+
function array2tree(array, options = {}) {
|
|
16
|
+
const { primaryKey: id, parentKey: pid, childrenKey: children, createRoot, parentRefKey } = {
|
|
17
|
+
primaryKey: 'id',
|
|
18
|
+
parentKey: 'pid',
|
|
19
|
+
childrenKey: 'children',
|
|
20
|
+
createRoot: false,
|
|
21
|
+
parentRefKey: false,
|
|
22
|
+
...options
|
|
23
|
+
};
|
|
24
|
+
const pRefKey = parentRefKey &&
|
|
25
|
+
(typeof parentRefKey === 'string' ? parentRefKey : '_parent');
|
|
26
|
+
const nodeMap = {};
|
|
27
|
+
const treeNodes = [];
|
|
28
|
+
utils.isArr(array) &&
|
|
29
|
+
array.forEach((item) => {
|
|
30
|
+
!utils.hasOwnProp(nodeMap, item[id]) &&
|
|
31
|
+
(nodeMap[item[id]] = Object.assign({}, item, createNode(children)));
|
|
32
|
+
utils.hasOwnProp(nodeMap, item[pid]) &&
|
|
33
|
+
nodeMap[item[pid]][children].push(Object.assign(nodeMap[item[id]], pRefKey ? { [pRefKey]: nodeMap[item[pid]] } : {}));
|
|
34
|
+
!item[pid] && treeNodes.push(nodeMap[item[id]]);
|
|
35
|
+
});
|
|
36
|
+
if (utils.isFn(createRoot)) {
|
|
37
|
+
return createRoot(treeNodes);
|
|
38
|
+
}
|
|
39
|
+
else if (createRoot) {
|
|
40
|
+
return { [children]: treeNodes };
|
|
41
|
+
}
|
|
42
|
+
return treeNodes;
|
|
43
|
+
}
|
|
44
|
+
function nodeChildFilter(node, childrenKey) {
|
|
45
|
+
const newNode = {};
|
|
46
|
+
for (const i in node) {
|
|
47
|
+
i !== childrenKey && (newNode[i] = node[i]);
|
|
48
|
+
}
|
|
49
|
+
return newNode;
|
|
50
|
+
}
|
|
51
|
+
function tree2array(tree, options = {}) {
|
|
52
|
+
const { primaryKey: id, parentKey: pid, childrenKey: children, hasParentKey, returnObject } = Object.assign({
|
|
53
|
+
hasParentKey: true,
|
|
54
|
+
primaryKey: 'id',
|
|
55
|
+
parentKey: 'pid',
|
|
56
|
+
childrenKey: 'children',
|
|
57
|
+
returnObject: false
|
|
58
|
+
}, options);
|
|
59
|
+
const nodes = returnObject ? {} : [];
|
|
60
|
+
if (!utils.isArr(tree) && typeof tree !== 'object')
|
|
61
|
+
return nodes;
|
|
62
|
+
function getNode(node, parentId, root = false) {
|
|
63
|
+
const baseNode = hasParentKey ? {} : { [pid]: parentId };
|
|
64
|
+
if (!root) {
|
|
65
|
+
const newNode = Object.assign(baseNode, nodeChildFilter(node, children));
|
|
66
|
+
returnObject
|
|
67
|
+
? (nodes[node[id]] = newNode)
|
|
68
|
+
: nodes.push(newNode);
|
|
69
|
+
}
|
|
70
|
+
if (utils.isArr(node[children]) && node[children].length) {
|
|
71
|
+
node[children].forEach((childNode) => getNode(childNode, node[id]));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const rootTree = utils.isArr(tree) ? createNode(children, tree) : tree;
|
|
75
|
+
getNode(rootTree, null, true);
|
|
76
|
+
return nodes;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* 分析id唯一的树节点,得到不同结构的数据
|
|
80
|
+
* @param treeData 树数据
|
|
81
|
+
* @param options 配置项
|
|
82
|
+
* @param keys 可指定的数据类型的key,默认返回完整数据
|
|
83
|
+
* @returns
|
|
84
|
+
*/
|
|
85
|
+
function treeAnalyse(treeData, options, keys) {
|
|
86
|
+
const result = {
|
|
87
|
+
nodes: [],
|
|
88
|
+
childKeysMaps: {},
|
|
89
|
+
keyNodeMap: {},
|
|
90
|
+
disabledKeys: []
|
|
91
|
+
};
|
|
92
|
+
const moduleKeys = Array.isArray(keys)
|
|
93
|
+
? keys
|
|
94
|
+
: ['nodes', 'keyNodeMap', 'childKeysMaps', 'disabledKeys'];
|
|
95
|
+
const { primaryKey, labelKey, disabledKey, childrenKey } = {
|
|
96
|
+
primaryKey: 'id',
|
|
97
|
+
labelKey: 'name',
|
|
98
|
+
childrenKey: 'children',
|
|
99
|
+
disabledKey: 'disabled',
|
|
100
|
+
...options
|
|
101
|
+
};
|
|
102
|
+
const [hasNodes, hasCKM, hasKNM, hasDK] = Object.keys(result).map((m) => moduleKeys.includes(m));
|
|
103
|
+
const readTreeData = (nodes, parent) => {
|
|
104
|
+
nodes.forEach((node) => {
|
|
105
|
+
const { [primaryKey]: key, [labelKey]: label, [childrenKey]: children, [disabledKey]: disabled } = node;
|
|
106
|
+
let keyNode = undefined;
|
|
107
|
+
if (hasNodes) {
|
|
108
|
+
result.nodes.push(node);
|
|
109
|
+
}
|
|
110
|
+
if (hasKNM && key !== undefined) {
|
|
111
|
+
keyNode = { keyVlaue: key, keyLabel: label, parent, children: [] };
|
|
112
|
+
parent?.children.push(keyNode);
|
|
113
|
+
result.keyNodeMap[key] = keyNode;
|
|
114
|
+
}
|
|
115
|
+
if (hasDK && disabled && key !== undefined) {
|
|
116
|
+
result.disabledKeys.push(key);
|
|
117
|
+
}
|
|
118
|
+
if (Array.isArray(children) && children.length) {
|
|
119
|
+
if (hasCKM) {
|
|
120
|
+
result.childKeysMaps[key] = children.map((item) => item[primaryKey]);
|
|
121
|
+
}
|
|
122
|
+
readTreeData(children, keyNode);
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
};
|
|
126
|
+
treeData && readTreeData(treeData);
|
|
127
|
+
return result;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
exports.array2tree = array2tree;
|
|
131
|
+
exports.tree2array = tree2array;
|
|
132
|
+
exports.treeAnalyse = treeAnalyse;
|
package/dist/index.esm.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @wxhccc/es-util v2.0
|
|
2
|
+
* @wxhccc/es-util v2.1.0
|
|
3
3
|
* (c) 2022 wxhccc
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -82,6 +82,57 @@ function tree2array(tree, options = {}) {
|
|
|
82
82
|
const rootTree = isArr(tree) ? createNode(children, tree) : tree;
|
|
83
83
|
getNode(rootTree, null, true);
|
|
84
84
|
return nodes;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* 分析id唯一的树节点,得到不同结构的数据
|
|
88
|
+
* @param treeData 树数据
|
|
89
|
+
* @param options 配置项
|
|
90
|
+
* @param keys 可指定的数据类型的key,默认返回完整数据
|
|
91
|
+
* @returns
|
|
92
|
+
*/
|
|
93
|
+
function treeAnalyse(treeData, options, keys) {
|
|
94
|
+
const result = {
|
|
95
|
+
nodes: [],
|
|
96
|
+
childKeysMaps: {},
|
|
97
|
+
keyNodeMap: {},
|
|
98
|
+
disabledKeys: []
|
|
99
|
+
};
|
|
100
|
+
const moduleKeys = Array.isArray(keys)
|
|
101
|
+
? keys
|
|
102
|
+
: ['nodes', 'keyNodeMap', 'childKeysMaps', 'disabledKeys'];
|
|
103
|
+
const { primaryKey, labelKey, disabledKey, childrenKey } = {
|
|
104
|
+
primaryKey: 'id',
|
|
105
|
+
labelKey: 'name',
|
|
106
|
+
childrenKey: 'children',
|
|
107
|
+
disabledKey: 'disabled',
|
|
108
|
+
...options
|
|
109
|
+
};
|
|
110
|
+
const [hasNodes, hasCKM, hasKNM, hasDK] = Object.keys(result).map((m) => moduleKeys.includes(m));
|
|
111
|
+
const readTreeData = (nodes, parent) => {
|
|
112
|
+
nodes.forEach((node) => {
|
|
113
|
+
const { [primaryKey]: key, [labelKey]: label, [childrenKey]: children, [disabledKey]: disabled } = node;
|
|
114
|
+
let keyNode = undefined;
|
|
115
|
+
if (hasNodes) {
|
|
116
|
+
result.nodes.push(node);
|
|
117
|
+
}
|
|
118
|
+
if (hasKNM && key !== undefined) {
|
|
119
|
+
keyNode = { keyVlaue: key, keyLabel: label, parent, children: [] };
|
|
120
|
+
parent?.children.push(keyNode);
|
|
121
|
+
result.keyNodeMap[key] = keyNode;
|
|
122
|
+
}
|
|
123
|
+
if (hasDK && disabled && key !== undefined) {
|
|
124
|
+
result.disabledKeys.push(key);
|
|
125
|
+
}
|
|
126
|
+
if (Array.isArray(children) && children.length) {
|
|
127
|
+
if (hasCKM) {
|
|
128
|
+
result.childKeysMaps[key] = children.map((item) => item[primaryKey]);
|
|
129
|
+
}
|
|
130
|
+
readTreeData(children, keyNode);
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
};
|
|
134
|
+
treeData && readTreeData(treeData);
|
|
135
|
+
return result;
|
|
85
136
|
}
|
|
86
137
|
|
|
87
138
|
/* 身份证正则 */
|
|
@@ -391,7 +442,8 @@ function wrapPromise(promise, options) {
|
|
|
391
442
|
let isLocking = false;
|
|
392
443
|
const stateLock = (bool) => {
|
|
393
444
|
if (lockRefHandle) {
|
|
394
|
-
|
|
445
|
+
const [ref, key] = lockRefHandle;
|
|
446
|
+
ref[key] = bool;
|
|
395
447
|
}
|
|
396
448
|
if (lockSwitchHook) {
|
|
397
449
|
lockSwitchHook(bool);
|
|
@@ -399,7 +451,7 @@ function wrapPromise(promise, options) {
|
|
|
399
451
|
};
|
|
400
452
|
const checkLock = () => {
|
|
401
453
|
// use refHandle if state not update sync
|
|
402
|
-
return lockRefHandle ? lockRefHandle[0][lockRefHandle[1]] : false;
|
|
454
|
+
return lockRefHandle ? !!lockRefHandle[0][lockRefHandle[1]] : false;
|
|
403
455
|
};
|
|
404
456
|
if (lock) {
|
|
405
457
|
const isRefHandle = (val) => isArr(val) && val.length === 2;
|
|
@@ -700,7 +752,7 @@ function pageCommunicate(options) {
|
|
|
700
752
|
let bc;
|
|
701
753
|
const ls = window.localStorage;
|
|
702
754
|
const channelName = 'PAGE_COMMUNICATE_CHANNEL';
|
|
703
|
-
if (typeof BroadcastChannel !== undefined) {
|
|
755
|
+
if (typeof window.BroadcastChannel !== undefined) {
|
|
704
756
|
bc = new BroadcastChannel(channelName);
|
|
705
757
|
bc.addEventListener('message', onMessage);
|
|
706
758
|
}
|
|
@@ -854,4 +906,4 @@ const secondsToDuration = (number, maxUnit = 'h') => {
|
|
|
854
906
|
return result;
|
|
855
907
|
};
|
|
856
908
|
|
|
857
|
-
export { ChinaIdCardValid, NOMETHOD, array2tree, awaitWrapper, b64UriDecode, b64UriEncode, byteStringify, checkoutBy, createRAFTimer, eventTargetEmitter, filterNullable, formParamsSwitch, formParamsSwitchCreator, formulaValidate, isNullable, mapToObject, maskData, pageCommunicate, pickRenameKeys, safeJsonParse, secondsToDuration, switchNullToUndefined, tree2array, wp };
|
|
909
|
+
export { ChinaIdCardValid, NOMETHOD, array2tree, awaitWrapper, b64UriDecode, b64UriEncode, byteStringify, checkoutBy, createRAFTimer, eventTargetEmitter, filterNullable, formParamsSwitch, formParamsSwitchCreator, formulaValidate, isNullable, mapToObject, maskData, pageCommunicate, pickRenameKeys, safeJsonParse, secondsToDuration, switchNullToUndefined, tree2array, treeAnalyse, wp };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @wxhccc/es-util v2.0
|
|
2
|
+
* @wxhccc/es-util v2.1.0
|
|
3
3
|
* (c) 2022 wxhccc
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -86,6 +86,57 @@ function tree2array(tree, options = {}) {
|
|
|
86
86
|
const rootTree = isArr(tree) ? createNode(children, tree) : tree;
|
|
87
87
|
getNode(rootTree, null, true);
|
|
88
88
|
return nodes;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* 分析id唯一的树节点,得到不同结构的数据
|
|
92
|
+
* @param treeData 树数据
|
|
93
|
+
* @param options 配置项
|
|
94
|
+
* @param keys 可指定的数据类型的key,默认返回完整数据
|
|
95
|
+
* @returns
|
|
96
|
+
*/
|
|
97
|
+
function treeAnalyse(treeData, options, keys) {
|
|
98
|
+
const result = {
|
|
99
|
+
nodes: [],
|
|
100
|
+
childKeysMaps: {},
|
|
101
|
+
keyNodeMap: {},
|
|
102
|
+
disabledKeys: []
|
|
103
|
+
};
|
|
104
|
+
const moduleKeys = Array.isArray(keys)
|
|
105
|
+
? keys
|
|
106
|
+
: ['nodes', 'keyNodeMap', 'childKeysMaps', 'disabledKeys'];
|
|
107
|
+
const { primaryKey, labelKey, disabledKey, childrenKey } = {
|
|
108
|
+
primaryKey: 'id',
|
|
109
|
+
labelKey: 'name',
|
|
110
|
+
childrenKey: 'children',
|
|
111
|
+
disabledKey: 'disabled',
|
|
112
|
+
...options
|
|
113
|
+
};
|
|
114
|
+
const [hasNodes, hasCKM, hasKNM, hasDK] = Object.keys(result).map((m) => moduleKeys.includes(m));
|
|
115
|
+
const readTreeData = (nodes, parent) => {
|
|
116
|
+
nodes.forEach((node) => {
|
|
117
|
+
const { [primaryKey]: key, [labelKey]: label, [childrenKey]: children, [disabledKey]: disabled } = node;
|
|
118
|
+
let keyNode = undefined;
|
|
119
|
+
if (hasNodes) {
|
|
120
|
+
result.nodes.push(node);
|
|
121
|
+
}
|
|
122
|
+
if (hasKNM && key !== undefined) {
|
|
123
|
+
keyNode = { keyVlaue: key, keyLabel: label, parent, children: [] };
|
|
124
|
+
parent?.children.push(keyNode);
|
|
125
|
+
result.keyNodeMap[key] = keyNode;
|
|
126
|
+
}
|
|
127
|
+
if (hasDK && disabled && key !== undefined) {
|
|
128
|
+
result.disabledKeys.push(key);
|
|
129
|
+
}
|
|
130
|
+
if (Array.isArray(children) && children.length) {
|
|
131
|
+
if (hasCKM) {
|
|
132
|
+
result.childKeysMaps[key] = children.map((item) => item[primaryKey]);
|
|
133
|
+
}
|
|
134
|
+
readTreeData(children, keyNode);
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
};
|
|
138
|
+
treeData && readTreeData(treeData);
|
|
139
|
+
return result;
|
|
89
140
|
}
|
|
90
141
|
|
|
91
142
|
/* 身份证正则 */
|
|
@@ -395,7 +446,8 @@ function wrapPromise(promise, options) {
|
|
|
395
446
|
let isLocking = false;
|
|
396
447
|
const stateLock = (bool) => {
|
|
397
448
|
if (lockRefHandle) {
|
|
398
|
-
|
|
449
|
+
const [ref, key] = lockRefHandle;
|
|
450
|
+
ref[key] = bool;
|
|
399
451
|
}
|
|
400
452
|
if (lockSwitchHook) {
|
|
401
453
|
lockSwitchHook(bool);
|
|
@@ -403,7 +455,7 @@ function wrapPromise(promise, options) {
|
|
|
403
455
|
};
|
|
404
456
|
const checkLock = () => {
|
|
405
457
|
// use refHandle if state not update sync
|
|
406
|
-
return lockRefHandle ? lockRefHandle[0][lockRefHandle[1]] : false;
|
|
458
|
+
return lockRefHandle ? !!lockRefHandle[0][lockRefHandle[1]] : false;
|
|
407
459
|
};
|
|
408
460
|
if (lock) {
|
|
409
461
|
const isRefHandle = (val) => isArr(val) && val.length === 2;
|
|
@@ -704,7 +756,7 @@ function pageCommunicate(options) {
|
|
|
704
756
|
let bc;
|
|
705
757
|
const ls = window.localStorage;
|
|
706
758
|
const channelName = 'PAGE_COMMUNICATE_CHANNEL';
|
|
707
|
-
if (typeof BroadcastChannel !== undefined) {
|
|
759
|
+
if (typeof window.BroadcastChannel !== undefined) {
|
|
708
760
|
bc = new BroadcastChannel(channelName);
|
|
709
761
|
bc.addEventListener('message', onMessage);
|
|
710
762
|
}
|
|
@@ -881,4 +933,5 @@ exports.safeJsonParse = safeJsonParse;
|
|
|
881
933
|
exports.secondsToDuration = secondsToDuration;
|
|
882
934
|
exports.switchNullToUndefined = switchNullToUndefined;
|
|
883
935
|
exports.tree2array = tree2array;
|
|
936
|
+
exports.treeAnalyse = treeAnalyse;
|
|
884
937
|
exports.wp = wp;
|
package/dist/index.min.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @wxhccc/es-util v2.0
|
|
2
|
+
* @wxhccc/es-util v2.1.0
|
|
3
3
|
* (c) 2022 wxhccc
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
6
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).EsUtil={})}(this,(function(e){"use strict";const{hasOwnProperty:t,toString:n}=Object.prototype,r=(e,t)=>{Object.keys(e).forEach(((n,r)=>t(n,e[n],r)))},o=e=>"function"==typeof e,s=Array.isArray,i=e=>{const t=(r=e,n.call(r)).match(/^\[object (.*)\]$/);var r;return t?t[1]:""},a=e=>"Object"===i(e),c=(e,n)=>t.call(e,n);function l(e,t=[]){return{[e]:t}}const u=/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i;const d={telphone:{startCharIndex:-8,endCharIndex:-5},idcard:{startCharIndex:-12,endCharIndex:-5}};async function f(e){try{return[null,await e]}catch(e){return[e,void 0]}}const p=function(e,t){const{wrap:n,lock:r,syncRefHandle:i}={...t};let a,c,l=!1,u=!1;const d=e=>{c&&(c[0][c[1]]=e),a&&a(e)};if(r){const e=e=>s(e)&&2===e.length;e(r)?c=r:o(r)&&(a=r,e(i)&&(c=i)),l=!(!a&&!c),l&&(u=!!c&&c[0][c[1]])}let p;if(o(e)){const t=u?Promise.resolve(void 0):e();p=n?f(t):t}else p=n?f(e):e;return p instanceof Promise&&l&&!u&&(d(!0),p.finally((()=>d(!1)))),p};function m(e="",t){try{return JSON.parse(e)}catch(e){return t}}const h=e=>""===e||null==e,y=(e,t)=>{const n={};return r(e,((e,r)=>{h(r)||(t?s(r)?n[e]=r.map((e=>a(e)?y(e):e)):n[e]=a(r)?y(r):r:n[e]=r)})),n},g=e=>{if(null!==e){if(s(e))return e.map(g);if(a(e)){const t={};return r(e,((e,n)=>{t[e]=g(n)})),t}return e}},b=(e,t,n)=>{const i=Object.keys(t),a={},c={};r(e,(t=>{i.includes(t)?a[t]=e[t]:c[t]=e[t]}));const l=Object.keys(a);if(0===l.length)return e;const{filterNullable:u,dateFormat:d}={filterNullable:!0,...n},f=l.reduce(((e,n)=>{const r=a[n],i=t[n];if(!r||!i)return e;if("join"===i||"pop"===i)s(r)&&r.length&&(e[n]="join"===i?r.join(","):r.slice(-1)[0]);else if(2===i.length||3===i.length){if(!r||2!==r.length)return e;const[t,n,s]=i,[a,c]=r;Object.assign(e,{[t]:o(d)?d(a,s):a,[n]:o(d)?d(c,s):c})}return e}),{}),p={...c,...f};return u?y(p):p},j=e=>"string"==typeof e,x=Symbol("NOMETHOD");function M(e){const t=new Map([[x,new Set]]),{name:n,customHanlderCreator:r}=e||{},s=o(r)?r(t):null,i=/\|-[a-z]+-\|/,a=(e,...t)=>{try{e(...t)}catch(e){console.error(e)}},c=o(s)?s:e=>{const{method:r,data:o,originEmitterName:s,targetEmitterName:c}=e||[];if(r&&"string"==typeof r){const e=[];t.forEach(((t,n)=>{if("string"==typeof n&&n.startsWith(r)){const[,r]=n.split(i);r&&s&&r!==s||e.push(...t)}})),!e.length||n&&c&&n!==c||e.forEach((e=>a(e,o)))}const l=t.get(x);l&&l.forEach((t=>a(t,o,e)))},l=(e,t)=>{const{limitFrom:n="",namespace:r=""}=t||{};return(n||r)&&"string"==typeof e?`${e}|-from-|${n}|-ns-|${r}`:e},u=(e,t,r)=>j(e)?{method:e,data:t,...r&&j(r)?{targetEmitterName:r}:{},...n&&j(n)?{originEmitterName:n}:{}}:e;return{name:n,rootEventListener:c,on:(e,n,r)=>{if("symbol"==typeof e&&e!==x)return;const o=l(e,r);t.has(o)||t.set(o,new Set);t.get(o)?.add(n)},off:(e,n,r)=>{if("symbol"==typeof e&&e!==x)return;const{namespace:o}=r||{};if(o&&!e)return void t.forEach(((e,n)=>{"string"==typeof n&&n.endsWith(o)&&t.delete(n)}));const s=l(e,r);n?t.get(s)?.delete(n):t.delete(s)},emit:(...e)=>{const t=u(...e);c(t)},createPayload:u,removeAllListeners:()=>{t.clear()},getMethodNames:e=>{if(!e){const e=[];return t.forEach(((t,n)=>j(n)&&e.push(n.split(i)))),e}const n=[];return t.forEach(((e,t)=>j(t)&&n.push(t))),n},getListeners:(e,n)=>{if("symbol"==typeof e)return e===x?Array.from(t.get(x)||[]):[];const r=l(e,n),o=t.get(r);return o?Array.from(o):[]}}}e.ChinaIdCardValid=function(e){const t=e.toString().toUpperCase();return u.test(t)&&["11","12","13","14","15","21","22","23","31","32","33","34","35","36","37","41","42","43","44","45","46","50","51","52","53","54","61","62","63","64","65","71","81","82","91"].includes(t.substr(0,2))&&(()=>{if(18===t.length){const e=t.split(""),n=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2],r=[1,0,"X",9,8,7,6,5,4,3,2];let o=0,s=0,i=0;for(let t=0;t<17;t++)s=parseInt(e[t]),i=n[t],o+=s*i;return r[o%11].toString()===e[17]}return!0})()},e.NOMETHOD=x,e.array2tree=function(e,t={}){const{primaryKey:n,parentKey:r,childrenKey:i,createRoot:a,parentRefKey:u}={primaryKey:"id",parentKey:"pid",childrenKey:"children",createRoot:!1,parentRefKey:!1,...t},d=u&&("string"==typeof u?u:"_parent"),f={},p=[];return s(e)&&e.forEach((e=>{!c(f,e[n])&&(f[e[n]]=Object.assign({},e,l(i))),c(f,e[r])&&f[e[r]][i].push(Object.assign(f[e[n]],d?{[d]:f[e[r]]}:{})),!e[r]&&p.push(f[e[n]])})),o(a)?a(p):a?{[i]:p}:p},e.awaitWrapper=f,e.b64UriDecode=e=>decodeURIComponent(window.atob(e)),e.b64UriEncode=e=>window.btoa(encodeURIComponent(e)),e.byteStringify=function(e,t){const n=Object.assign({standard:"jedec",unitLvl:"auto",precision:1,detail:!1},t),{standard:r,unitLvl:o,precision:i,detail:a}=n;let c=parseFloat(e);if(!Number.isFinite(c))return;const l=c<0?-1:1;c=Math.abs(c);const{base:u,unitMap:d}=((e,t)=>{const n={B:{expMax:0,units:{metric:"B",iec:"B",jedec:"B"}},K:{expMax:1,units:{metric:"kB",iec:"KiB",jedec:"KB"}},M:{expMax:2,units:{metric:"MB",iec:"MiB",jedec:"MB"}},G:{expMax:3,units:{metric:"GB",iec:"GiB",jedec:"GB"}},T:{expMax:4,units:{metric:"TB",iec:"TiB",jedec:"TB"}},P:{expMax:5,units:{metric:"PB",iec:"PiB",jedec:"PB"}},E:{expMax:6,units:{metric:"EB",iec:"EiB",jedec:"EB"}},Z:{expMax:7,units:{metric:"ZB",iec:"ZiB",jedec:"ZB"}},Y:{expMax:8,units:{metric:"YB",iec:"YiB",jedec:"YB"}}},r={metric:1e3,iec:1024,jedec:1024};return{base:r[e]||r.jedec,unitMap:n[t]||Object.values(n)}})(r,o),f=e=>Number.isInteger(e)?e:e.toFixed(i);let p="",m=0;if(s(d))d.some((e=>{const t=Math.pow(u,e.expMax),n=c/t;return!(n>u)&&(p=e.units[r],m=f(n*l),!0)}));else{const e=Math.pow(u,d.expMax);p=d.units[r];m=f(c/e*l)}return a?{value:m,unit:p}:`${m} ${p}`},e.checkoutBy=function(e,t,n){return a(e)?s(t)?t.map((t=>e[t])):t&&a(t)?Object.keys(t).map((r=>{const o=t[r];return a(e[r])&&a(o)?n?n({},e[r],o):Object.assign({},e[r],o):o||e[r]})):Object.values(e):[]},e.createRAFTimer=e=>{const{autoStopWhenNoTask:t,autoStartWhenAddTask:n}={...e};let r=0,o=!0,s=0,i=0,a=[],c=!1;const l=e=>{const n=e-(i||e);i=e,s+=n,c&&(a=a.filter((e=>!e.needClear)),c=!1),!t||a.length?(a.forEach((e=>{const{callback:t,maxTime:r,runTime:o,elapsed:i,interval:a,needClear:l}=e;if(!l){if(r&&o>=r)return e.needClear=!0,void(c=!0);if(i>=a){try{t(s)}catch(e){}e.elapsed=0,e.runTime+=1}else e.elapsed+=n}})),r=window.requestAnimationFrame(l)):o=!0},u=()=>{r=window.requestAnimationFrame(l),o=!1},d=()=>{window.cancelAnimationFrame(r),o=!0};return{start:u,stop:d,pauseToggle:()=>{o?u():d()},addTask:(e,t,r)=>{e&&(n&&o&&u(),a.push({callback:e,elapsed:0,interval:t,maxTime:r,runTime:0}))},removeTask:e=>{a=a.filter((t=>t.callback!==e))},isPaused:()=>o}},e.eventTargetEmitter=M,e.filterNullable=y,e.formParamsSwitch=b,e.formParamsSwitchCreator=e=>(t,n,r)=>b(t,n,{dateFormat:e,...r}),e.formulaValidate=function(e,t){return e=e.replace(/\s/g,""),!/[+\-*/]{2,}/.test(e)&&!/\(\)/.test(e)&&!/\([+\-*/]/.test(e)&&!/[+\-*/]\)/.test(e)&&!/[^+\-*/]\(/.test(e)&&!/\)[^+\-*/]/.test(e)&&(()=>{const t=[];for(let n,r=0;r<e.length;r++)if(n=e.charAt(r),"("===n)t.push("(");else if(")"===n){if(!(t.length>0))return!1;t.pop()}return!t.length})()&&(!s(t)||(n=t,e.replace(/[()+\-*/]{1,}/g,"`").split("`").every((e=>!/[A-Z]/i.test(e)||n.includes(e)))));var n},e.isNullable=h,e.mapToObject=function(e,t="key",n="value"){const r={};return s(e)&&t&&n&&[t,n].every((e=>["string","function"].includes(typeof e)))&&e.forEach(((e,o)=>{const s="string"==typeof t?e[t]:t(e,o),i="string"==typeof n?e[n]:n(e,o);["string","number"].includes(typeof s)&&(r[s]=i)})),r},e.maskData=function(e,t){if("string"!=typeof e||!e)return"";const n=t&&t.mode&&d[t.mode]?d[t.mode]:{},{maskWith:r,startCharIndex:o=0,endCharIndex:s,startFrom:i,endUntil:a}={maskWith:"*",...n,...t};let c=e,l="",u="";const f=i?e.indexOf(i):-1;if(f>-1){const t=f+i.length;c=c.slice(t),l=e.slice(0,t)}const p=a?e.lastIndexOf(a):-1;p>-1&&(c=c.slice(0,p),u=e.slice(p));const m=c.split(""),h=[l],y=m.length,g=[o>=0?o:y+o,void 0!==s?s>=0?s:y+s:y-1];let[b,j]=g;return j=j>0&&j<y?j:y-1,b=b>=0&&b<=j?b:0,m.forEach(((e,t)=>{h.push(t>=b&&t<=j?r:e)})),h.push(u),h.join("")},e.pageCommunicate=function(e){const{messageHanlder:t,currentPage:n}=e||{},{emit:r,on:o,off:s,createPayload:i,removeAllListeners:a}=M({name:n,customHanlderCreator:t}),c=e=>r(e.data);let l;const u=window.localStorage,d="PAGE_COMMUNICATE_CHANNEL";if(void 0!==typeof BroadcastChannel)l=new BroadcastChannel(d),l.addEventListener("message",c);else{const e=()=>{const e=m(u.getItem(d)||"");e&&r(e)};window.addEventListener("storage",e)}return{on:o,off:s,send:(...e)=>{const t=i(...e);if(l)l.postMessage(t);else{const e=JSON.stringify({...t,ts:+new Date});u.setItem(d,e)}},destory:()=>{a(),l?l.close():u.removeItem(d)}}},e.pickRenameKeys=function(e,t){if(!(e&&a(e)&&t&&a(t)))return;const n={};for(const r in e)r in t&&(n[t[r]]=e[r]);return n},e.safeJsonParse=m,e.secondsToDuration=(e,t="h")=>{const n=Number.isInteger(e)?e:Math.round(e),r={s:n%60};switch(t){case"m":r.m=Math.floor(n/60);break;case"h":r.m=Math.floor(n%3600/60),r.h=Math.floor(n/3600);break;case"d":r.m=Math.floor(n%3600/60),r.h=Math.floor(n%86400/3600),r.d=Math.floor(n/3600/24)}return r},e.switchNullToUndefined=g,e.tree2array=function(e,t={}){const{primaryKey:n,parentKey:r,childrenKey:o,hasParentKey:i,returnObject:a}=Object.assign({hasParentKey:!0,primaryKey:"id",parentKey:"pid",childrenKey:"children",returnObject:!1},t),c=a?{}:[];return s(e)||"object"==typeof e?(function e(t,l,u=!1){const d=i?{}:{[r]:l};if(!u){const e=Object.assign(d,function(e,t){const n={};for(const r in e)r!==t&&(n[r]=e[r]);return n}(t,o));a?c[t[n]]=e:c.push(e)}s(t[o])&&t[o].length&&t[o].forEach((r=>e(r,t[n])))}(s(e)?l(o,e):e,null,!0),c):c},e.wp=p,Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
6
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).EsUtil={})}(this,(function(e){"use strict";const{hasOwnProperty:t,toString:n}=Object.prototype,r=(e,t)=>{Object.keys(e).forEach(((n,r)=>t(n,e[n],r)))},s=e=>"function"==typeof e,i=Array.isArray,o=e=>{const t=(r=e,n.call(r)).match(/^\[object (.*)\]$/);var r;return t?t[1]:""},a=e=>"Object"===o(e),c=(e,n)=>t.call(e,n);function l(e,t=[]){return{[e]:t}}const d=/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i;const u={telphone:{startCharIndex:-8,endCharIndex:-5},idcard:{startCharIndex:-12,endCharIndex:-5}};async function f(e){try{return[null,await e]}catch(e){return[e,void 0]}}const p=function(e,t){const{wrap:n,lock:r,syncRefHandle:o}={...t};let a,c,l=!1,d=!1;const u=e=>{if(c){const[t,n]=c;t[n]=e}a&&a(e)};if(r){const e=e=>i(e)&&2===e.length;e(r)?c=r:s(r)&&(a=r,e(o)&&(c=o)),l=!(!a&&!c),l&&(d=!!c&&!!c[0][c[1]])}let p;if(s(e)){const t=d?Promise.resolve(void 0):e();p=n?f(t):t}else p=n?f(e):e;return p instanceof Promise&&l&&!d&&(u(!0),p.finally((()=>u(!1)))),p};function m(e="",t){try{return JSON.parse(e)}catch(e){return t}}const h=e=>""===e||null==e,y=(e,t)=>{const n={};return r(e,((e,r)=>{h(r)||(t?i(r)?n[e]=r.map((e=>a(e)?y(e):e)):n[e]=a(r)?y(r):r:n[e]=r)})),n},g=e=>{if(null!==e){if(i(e))return e.map(g);if(a(e)){const t={};return r(e,((e,n)=>{t[e]=g(n)})),t}return e}},b=(e,t,n)=>{const o=Object.keys(t),a={},c={};r(e,(t=>{o.includes(t)?a[t]=e[t]:c[t]=e[t]}));const l=Object.keys(a);if(0===l.length)return e;const{filterNullable:d,dateFormat:u}={filterNullable:!0,...n},f=l.reduce(((e,n)=>{const r=a[n],o=t[n];if(!r||!o)return e;if("join"===o||"pop"===o)i(r)&&r.length&&(e[n]="join"===o?r.join(","):r.slice(-1)[0]);else if(2===o.length||3===o.length){if(!r||2!==r.length)return e;const[t,n,i]=o,[a,c]=r;Object.assign(e,{[t]:s(u)?u(a,i):a,[n]:s(u)?u(c,i):c})}return e}),{}),p={...c,...f};return d?y(p):p},M=e=>"string"==typeof e,j=Symbol("NOMETHOD");function x(e){const t=new Map([[j,new Set]]),{name:n,customHanlderCreator:r}=e||{},i=s(r)?r(t):null,o=/\|-[a-z]+-\|/,a=(e,...t)=>{try{e(...t)}catch(e){console.error(e)}},c=s(i)?i:e=>{const{method:r,data:s,originEmitterName:i,targetEmitterName:c}=e||[];if(r&&"string"==typeof r){const e=[];t.forEach(((t,n)=>{if("string"==typeof n&&n.startsWith(r)){const[,r]=n.split(o);r&&i&&r!==i||e.push(...t)}})),!e.length||n&&c&&n!==c||e.forEach((e=>a(e,s)))}const l=t.get(j);l&&l.forEach((t=>a(t,s,e)))},l=(e,t)=>{const{limitFrom:n="",namespace:r=""}=t||{};return(n||r)&&"string"==typeof e?`${e}|-from-|${n}|-ns-|${r}`:e},d=(e,t,r)=>M(e)?{method:e,data:t,...r&&M(r)?{targetEmitterName:r}:{},...n&&M(n)?{originEmitterName:n}:{}}:e;return{name:n,rootEventListener:c,on:(e,n,r)=>{if("symbol"==typeof e&&e!==j)return;const s=l(e,r);t.has(s)||t.set(s,new Set);t.get(s)?.add(n)},off:(e,n,r)=>{if("symbol"==typeof e&&e!==j)return;const{namespace:s}=r||{};if(s&&!e)return void t.forEach(((e,n)=>{"string"==typeof n&&n.endsWith(s)&&t.delete(n)}));const i=l(e,r);n?t.get(i)?.delete(n):t.delete(i)},emit:(...e)=>{const t=d(...e);c(t)},createPayload:d,removeAllListeners:()=>{t.clear()},getMethodNames:e=>{if(!e){const e=[];return t.forEach(((t,n)=>M(n)&&e.push(n.split(o)))),e}const n=[];return t.forEach(((e,t)=>M(t)&&n.push(t))),n},getListeners:(e,n)=>{if("symbol"==typeof e)return e===j?Array.from(t.get(j)||[]):[];const r=l(e,n),s=t.get(r);return s?Array.from(s):[]}}}e.ChinaIdCardValid=function(e){const t=e.toString().toUpperCase();return d.test(t)&&["11","12","13","14","15","21","22","23","31","32","33","34","35","36","37","41","42","43","44","45","46","50","51","52","53","54","61","62","63","64","65","71","81","82","91"].includes(t.substr(0,2))&&(()=>{if(18===t.length){const e=t.split(""),n=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2],r=[1,0,"X",9,8,7,6,5,4,3,2];let s=0,i=0,o=0;for(let t=0;t<17;t++)i=parseInt(e[t]),o=n[t],s+=i*o;return r[s%11].toString()===e[17]}return!0})()},e.NOMETHOD=j,e.array2tree=function(e,t={}){const{primaryKey:n,parentKey:r,childrenKey:o,createRoot:a,parentRefKey:d}={primaryKey:"id",parentKey:"pid",childrenKey:"children",createRoot:!1,parentRefKey:!1,...t},u=d&&("string"==typeof d?d:"_parent"),f={},p=[];return i(e)&&e.forEach((e=>{!c(f,e[n])&&(f[e[n]]=Object.assign({},e,l(o))),c(f,e[r])&&f[e[r]][o].push(Object.assign(f[e[n]],u?{[u]:f[e[r]]}:{})),!e[r]&&p.push(f[e[n]])})),s(a)?a(p):a?{[o]:p}:p},e.awaitWrapper=f,e.b64UriDecode=e=>decodeURIComponent(window.atob(e)),e.b64UriEncode=e=>window.btoa(encodeURIComponent(e)),e.byteStringify=function(e,t){const n=Object.assign({standard:"jedec",unitLvl:"auto",precision:1,detail:!1},t),{standard:r,unitLvl:s,precision:o,detail:a}=n;let c=parseFloat(e);if(!Number.isFinite(c))return;const l=c<0?-1:1;c=Math.abs(c);const{base:d,unitMap:u}=((e,t)=>{const n={B:{expMax:0,units:{metric:"B",iec:"B",jedec:"B"}},K:{expMax:1,units:{metric:"kB",iec:"KiB",jedec:"KB"}},M:{expMax:2,units:{metric:"MB",iec:"MiB",jedec:"MB"}},G:{expMax:3,units:{metric:"GB",iec:"GiB",jedec:"GB"}},T:{expMax:4,units:{metric:"TB",iec:"TiB",jedec:"TB"}},P:{expMax:5,units:{metric:"PB",iec:"PiB",jedec:"PB"}},E:{expMax:6,units:{metric:"EB",iec:"EiB",jedec:"EB"}},Z:{expMax:7,units:{metric:"ZB",iec:"ZiB",jedec:"ZB"}},Y:{expMax:8,units:{metric:"YB",iec:"YiB",jedec:"YB"}}},r={metric:1e3,iec:1024,jedec:1024};return{base:r[e]||r.jedec,unitMap:n[t]||Object.values(n)}})(r,s),f=e=>Number.isInteger(e)?e:e.toFixed(o);let p="",m=0;if(i(u))u.some((e=>{const t=Math.pow(d,e.expMax),n=c/t;return!(n>d)&&(p=e.units[r],m=f(n*l),!0)}));else{const e=Math.pow(d,u.expMax);p=u.units[r];m=f(c/e*l)}return a?{value:m,unit:p}:`${m} ${p}`},e.checkoutBy=function(e,t,n){return a(e)?i(t)?t.map((t=>e[t])):t&&a(t)?Object.keys(t).map((r=>{const s=t[r];return a(e[r])&&a(s)?n?n({},e[r],s):Object.assign({},e[r],s):s||e[r]})):Object.values(e):[]},e.createRAFTimer=e=>{const{autoStopWhenNoTask:t,autoStartWhenAddTask:n}={...e};let r=0,s=!0,i=0,o=0,a=[],c=!1;const l=e=>{const n=e-(o||e);o=e,i+=n,c&&(a=a.filter((e=>!e.needClear)),c=!1),!t||a.length?(a.forEach((e=>{const{callback:t,maxTime:r,runTime:s,elapsed:o,interval:a,needClear:l}=e;if(!l){if(r&&s>=r)return e.needClear=!0,void(c=!0);if(o>=a){try{t(i)}catch(e){}e.elapsed=0,e.runTime+=1}else e.elapsed+=n}})),r=window.requestAnimationFrame(l)):s=!0},d=()=>{r=window.requestAnimationFrame(l),s=!1},u=()=>{window.cancelAnimationFrame(r),s=!0};return{start:d,stop:u,pauseToggle:()=>{s?d():u()},addTask:(e,t,r)=>{e&&(n&&s&&d(),a.push({callback:e,elapsed:0,interval:t,maxTime:r,runTime:0}))},removeTask:e=>{a=a.filter((t=>t.callback!==e))},isPaused:()=>s}},e.eventTargetEmitter=x,e.filterNullable=y,e.formParamsSwitch=b,e.formParamsSwitchCreator=e=>(t,n,r)=>b(t,n,{dateFormat:e,...r}),e.formulaValidate=function(e,t){return e=e.replace(/\s/g,""),!/[+\-*/]{2,}/.test(e)&&!/\(\)/.test(e)&&!/\([+\-*/]/.test(e)&&!/[+\-*/]\)/.test(e)&&!/[^+\-*/]\(/.test(e)&&!/\)[^+\-*/]/.test(e)&&(()=>{const t=[];for(let n,r=0;r<e.length;r++)if(n=e.charAt(r),"("===n)t.push("(");else if(")"===n){if(!(t.length>0))return!1;t.pop()}return!t.length})()&&(!i(t)||(n=t,e.replace(/[()+\-*/]{1,}/g,"`").split("`").every((e=>!/[A-Z]/i.test(e)||n.includes(e)))));var n},e.isNullable=h,e.mapToObject=function(e,t="key",n="value"){const r={};return i(e)&&t&&n&&[t,n].every((e=>["string","function"].includes(typeof e)))&&e.forEach(((e,s)=>{const i="string"==typeof t?e[t]:t(e,s),o="string"==typeof n?e[n]:n(e,s);["string","number"].includes(typeof i)&&(r[i]=o)})),r},e.maskData=function(e,t){if("string"!=typeof e||!e)return"";const n=t&&t.mode&&u[t.mode]?u[t.mode]:{},{maskWith:r,startCharIndex:s=0,endCharIndex:i,startFrom:o,endUntil:a}={maskWith:"*",...n,...t};let c=e,l="",d="";const f=o?e.indexOf(o):-1;if(f>-1){const t=f+o.length;c=c.slice(t),l=e.slice(0,t)}const p=a?e.lastIndexOf(a):-1;p>-1&&(c=c.slice(0,p),d=e.slice(p));const m=c.split(""),h=[l],y=m.length,g=[s>=0?s:y+s,void 0!==i?i>=0?i:y+i:y-1];let[b,M]=g;return M=M>0&&M<y?M:y-1,b=b>=0&&b<=M?b:0,m.forEach(((e,t)=>{h.push(t>=b&&t<=M?r:e)})),h.push(d),h.join("")},e.pageCommunicate=function(e){const{messageHanlder:t,currentPage:n}=e||{},{emit:r,on:s,off:i,createPayload:o,removeAllListeners:a}=x({name:n,customHanlderCreator:t}),c=e=>r(e.data);let l;const d=window.localStorage,u="PAGE_COMMUNICATE_CHANNEL";if(void 0!==typeof window.BroadcastChannel)l=new BroadcastChannel(u),l.addEventListener("message",c);else{const e=()=>{const e=m(d.getItem(u)||"");e&&r(e)};window.addEventListener("storage",e)}return{on:s,off:i,send:(...e)=>{const t=o(...e);if(l)l.postMessage(t);else{const e=JSON.stringify({...t,ts:+new Date});d.setItem(u,e)}},destory:()=>{a(),l?l.close():d.removeItem(u)}}},e.pickRenameKeys=function(e,t){if(!(e&&a(e)&&t&&a(t)))return;const n={};for(const r in e)r in t&&(n[t[r]]=e[r]);return n},e.safeJsonParse=m,e.secondsToDuration=(e,t="h")=>{const n=Number.isInteger(e)?e:Math.round(e),r={s:n%60};switch(t){case"m":r.m=Math.floor(n/60);break;case"h":r.m=Math.floor(n%3600/60),r.h=Math.floor(n/3600);break;case"d":r.m=Math.floor(n%3600/60),r.h=Math.floor(n%86400/3600),r.d=Math.floor(n/3600/24)}return r},e.switchNullToUndefined=g,e.tree2array=function(e,t={}){const{primaryKey:n,parentKey:r,childrenKey:s,hasParentKey:o,returnObject:a}=Object.assign({hasParentKey:!0,primaryKey:"id",parentKey:"pid",childrenKey:"children",returnObject:!1},t),c=a?{}:[];return i(e)||"object"==typeof e?(function e(t,l,d=!1){const u=o?{}:{[r]:l};if(!d){const e=Object.assign(u,function(e,t){const n={};for(const r in e)r!==t&&(n[r]=e[r]);return n}(t,s));a?c[t[n]]=e:c.push(e)}i(t[s])&&t[s].length&&t[s].forEach((r=>e(r,t[n])))}(i(e)?l(s,e):e,null,!0),c):c},e.treeAnalyse=function(e,t,n){const r={nodes:[],childKeysMaps:{},keyNodeMap:{},disabledKeys:[]},s=Array.isArray(n)?n:["nodes","keyNodeMap","childKeysMaps","disabledKeys"],{primaryKey:i,labelKey:o,disabledKey:a,childrenKey:c}={primaryKey:"id",labelKey:"name",childrenKey:"children",disabledKey:"disabled",...t},[l,d,u,f]=Object.keys(r).map((e=>s.includes(e))),p=(e,t)=>{e.forEach((e=>{const{[i]:n,[o]:s,[c]:m,[a]:h}=e;let y;l&&r.nodes.push(e),u&&void 0!==n&&(y={keyVlaue:n,keyLabel:s,parent:t,children:[]},t?.children.push(y),r.keyNodeMap[n]=y),f&&h&&void 0!==n&&r.disabledKeys.push(n),Array.isArray(m)&&m.length&&(d&&(r.childKeysMaps[n]=m.map((e=>e[i]))),p(m,y))}))};return e&&p(e),r},e.wp=p,Object.defineProperty(e,"__esModule",{value:!0})}));
|
package/dist/object-array.js
CHANGED
package/dist/optional.js
CHANGED
package/dist/page-communicate.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @wxhccc/es-util v2.0
|
|
2
|
+
* @wxhccc/es-util v2.1.0
|
|
3
3
|
* (c) 2022 wxhccc
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -26,7 +26,7 @@ function pageCommunicate(options) {
|
|
|
26
26
|
let bc;
|
|
27
27
|
const ls = window.localStorage;
|
|
28
28
|
const channelName = 'PAGE_COMMUNICATE_CHANNEL';
|
|
29
|
-
if (typeof BroadcastChannel !== undefined) {
|
|
29
|
+
if (typeof window.BroadcastChannel !== undefined) {
|
|
30
30
|
bc = new BroadcastChannel(channelName);
|
|
31
31
|
bc.addEventListener('message', onMessage);
|
|
32
32
|
}
|
package/dist/promise.d.ts
CHANGED
|
@@ -4,10 +4,11 @@
|
|
|
4
4
|
* @returns Promise<[K, undefined] | [null, T]>
|
|
5
5
|
*/
|
|
6
6
|
export declare function awaitWrapper<T, K = Error>(promise: Promise<T>): Promise<[null, T] | [K, undefined]>;
|
|
7
|
-
|
|
8
|
-
export declare type LockRefHandle<T extends {
|
|
7
|
+
export declare type BoolRef = {
|
|
9
8
|
[key: string]: boolean;
|
|
10
|
-
}
|
|
9
|
+
};
|
|
10
|
+
/** 防止多次promise函数运行控制器,对于响应式系统,可以同时用作BoolSwitch */
|
|
11
|
+
export declare type LockRefHandle<T = BoolRef> = [T, keyof T];
|
|
11
12
|
/** loading等状态的切换函数 */
|
|
12
13
|
export declare type BoolSwitch = (val: boolean) => unknown;
|
|
13
14
|
/**
|
|
@@ -15,25 +16,25 @@ export declare type BoolSwitch = (val: boolean) => unknown;
|
|
|
15
16
|
* @param promise promise
|
|
16
17
|
* @param wrap whether use awaitWrap to wrap result
|
|
17
18
|
*/
|
|
18
|
-
export interface WpOptions {
|
|
19
|
+
export interface WpOptions<R = BoolRef> {
|
|
19
20
|
/** whether use `awaitWrapper` to wrap then promise. */
|
|
20
21
|
wrap?: boolean;
|
|
21
22
|
/** useful in Hook / Composition Api, you can pass setXXX to method */
|
|
22
|
-
lock?: BoolSwitch | LockRefHandle
|
|
23
|
+
lock?: BoolSwitch | LockRefHandle<R>;
|
|
23
24
|
/** when you need function and syncRefHandle at sametime, in react hooks */
|
|
24
|
-
syncRefHandle?: LockRefHandle
|
|
25
|
+
syncRefHandle?: LockRefHandle<R>;
|
|
25
26
|
}
|
|
26
27
|
declare type WpReturn<T> = Promise<T | undefined>;
|
|
27
28
|
declare type WpArrReturn<T> = Promise<[null, T] | [Error, undefined]>;
|
|
28
29
|
declare type WpMayLockArrReturn<T> = Promise<[null, T] | [Error, undefined]>;
|
|
29
30
|
declare type WpPromise<T> = Promise<T> | (() => Promise<T>);
|
|
30
|
-
declare function wrapPromise<T>(promise: WpPromise<T>, options?: WpOptions & {
|
|
31
|
+
declare function wrapPromise<T, R = BoolRef>(promise: WpPromise<T>, options?: WpOptions<R> & {
|
|
31
32
|
wrap?: false;
|
|
32
33
|
}): WpReturn<T>;
|
|
33
|
-
declare function wrapPromise<T>(promise: Promise<T>, options?: WpOptions & {
|
|
34
|
+
declare function wrapPromise<T, R = BoolRef>(promise: Promise<T>, options?: WpOptions<R> & {
|
|
34
35
|
wrap: true;
|
|
35
36
|
}): WpArrReturn<T>;
|
|
36
|
-
declare function wrapPromise<T>(promise: () => Promise<T>, options?: WpOptions & {
|
|
37
|
+
declare function wrapPromise<T, R = BoolRef>(promise: () => Promise<T>, options?: WpOptions<R> & {
|
|
37
38
|
wrap: true;
|
|
38
39
|
}): WpMayLockArrReturn<T>;
|
|
39
40
|
/** short for method `wrapPromise` */
|
package/dist/promise.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @wxhccc/es-util v2.0
|
|
2
|
+
* @wxhccc/es-util v2.1.0
|
|
3
3
|
* (c) 2022 wxhccc
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -31,7 +31,8 @@ function wrapPromise(promise, options) {
|
|
|
31
31
|
let isLocking = false;
|
|
32
32
|
const stateLock = (bool) => {
|
|
33
33
|
if (lockRefHandle) {
|
|
34
|
-
|
|
34
|
+
const [ref, key] = lockRefHandle;
|
|
35
|
+
ref[key] = bool;
|
|
35
36
|
}
|
|
36
37
|
if (lockSwitchHook) {
|
|
37
38
|
lockSwitchHook(bool);
|
|
@@ -39,7 +40,7 @@ function wrapPromise(promise, options) {
|
|
|
39
40
|
};
|
|
40
41
|
const checkLock = () => {
|
|
41
42
|
// use refHandle if state not update sync
|
|
42
|
-
return lockRefHandle ? lockRefHandle[0][lockRefHandle[1]] : false;
|
|
43
|
+
return lockRefHandle ? !!lockRefHandle[0][lockRefHandle[1]] : false;
|
|
43
44
|
};
|
|
44
45
|
if (lock) {
|
|
45
46
|
const isRefHandle = (val) => utils.isArr(val) && val.length === 2;
|
package/dist/raf-timer.js
CHANGED
package/dist/types.d.ts
CHANGED
package/dist/utils.js
CHANGED
package/dist/validate.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wxhccc/es-util",
|
|
3
|
-
"version": "2.0
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"description": "A library that contains some useful methods",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.esm.js",
|
|
@@ -23,7 +23,11 @@
|
|
|
23
23
|
"validate",
|
|
24
24
|
"mapToObject",
|
|
25
25
|
"string-switch",
|
|
26
|
-
"mask data"
|
|
26
|
+
"mask data",
|
|
27
|
+
"event emitter",
|
|
28
|
+
"promise",
|
|
29
|
+
"requestAnimationFrame",
|
|
30
|
+
"page communicate"
|
|
27
31
|
],
|
|
28
32
|
"author": "wxhccc",
|
|
29
33
|
"license": "MIT",
|