@wxhccc/es-util 2.0.2 → 2.1.1

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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2019 hjw
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1
+ MIT License
2
+
3
+ Copyright (c) 2019 hjw
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
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 {
@@ -18,7 +23,7 @@ interface NodeOptions extends Options {
18
23
  hasParentKey?: boolean;
19
24
  returnObject?: boolean;
20
25
  }
21
- declare type Tree = TreeNode[] | {
26
+ type Tree = TreeNode[] | {
22
27
  [children: string]: TreeNode[];
23
28
  };
24
29
  /**
@@ -42,8 +47,8 @@ export declare function array2tree(array: Node[], options: TreeOptions & {
42
47
  export declare function array2tree<T = any>(array: Node[], options: TreeOptions & {
43
48
  createNode: AnyFunction<T>;
44
49
  }): T;
45
- declare type Nodes = Node[];
46
- declare type NodeMap = {
50
+ type Nodes = Node[];
51
+ type NodeMap = {
47
52
  [id: string]: Node;
48
53
  };
49
54
  /**
@@ -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
+ 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,149 @@
1
+ /*!
2
+ * @wxhccc/es-util v2.1.1
3
+ * (c) 2023 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
+ if (utils.isArr(array)) {
29
+ const unsortChildren = [];
30
+ const transform = (items) => {
31
+ items.forEach((item) => {
32
+ if (!utils.hasOwnProp(nodeMap, item[id])) {
33
+ nodeMap[item[id]] = { ...item, ...createNode(children) };
34
+ }
35
+ if (!item[pid]) {
36
+ treeNodes.push(nodeMap[item[id]]);
37
+ }
38
+ else if (utils.hasOwnProp(nodeMap, item[pid])) {
39
+ nodeMap[item[pid]][children].push(Object.assign(nodeMap[item[id]], pRefKey ? { [pRefKey]: nodeMap[item[pid]] } : {}));
40
+ }
41
+ else {
42
+ unsortChildren.push(item);
43
+ }
44
+ });
45
+ };
46
+ transform(array);
47
+ console.log(1111, unsortChildren);
48
+ // 如果有父节点顺序在后的,再循环一次
49
+ if (unsortChildren.length) {
50
+ transform(unsortChildren);
51
+ }
52
+ }
53
+ if (utils.isFn(createRoot)) {
54
+ return createRoot(treeNodes);
55
+ }
56
+ else if (createRoot) {
57
+ return { [children]: treeNodes };
58
+ }
59
+ return treeNodes;
60
+ }
61
+ function nodeChildFilter(node, childrenKey) {
62
+ const newNode = {};
63
+ for (const i in node) {
64
+ i !== childrenKey && (newNode[i] = node[i]);
65
+ }
66
+ return newNode;
67
+ }
68
+ function tree2array(tree, options = {}) {
69
+ const { primaryKey: id, parentKey: pid, childrenKey: children, hasParentKey, returnObject } = Object.assign({
70
+ hasParentKey: true,
71
+ primaryKey: 'id',
72
+ parentKey: 'pid',
73
+ childrenKey: 'children',
74
+ returnObject: false
75
+ }, options);
76
+ const nodes = returnObject ? {} : [];
77
+ if (!utils.isArr(tree) && typeof tree !== 'object')
78
+ return nodes;
79
+ function getNode(node, parentId, root = false) {
80
+ const baseNode = hasParentKey ? {} : { [pid]: parentId };
81
+ if (!root) {
82
+ const newNode = Object.assign(baseNode, nodeChildFilter(node, children));
83
+ returnObject
84
+ ? (nodes[node[id]] = newNode)
85
+ : nodes.push(newNode);
86
+ }
87
+ if (utils.isArr(node[children]) && node[children].length) {
88
+ node[children].forEach((childNode) => getNode(childNode, node[id]));
89
+ }
90
+ }
91
+ const rootTree = utils.isArr(tree) ? createNode(children, tree) : tree;
92
+ getNode(rootTree, null, true);
93
+ return nodes;
94
+ }
95
+ /**
96
+ * 分析id唯一的树节点,得到不同结构的数据
97
+ * @param treeData 树数据
98
+ * @param options 配置项
99
+ * @param keys 可指定的数据类型的key,默认返回完整数据
100
+ * @returns
101
+ */
102
+ function treeAnalyse(treeData, options, keys) {
103
+ const result = {
104
+ nodes: [],
105
+ childKeysMaps: {},
106
+ keyNodeMap: {},
107
+ disabledKeys: []
108
+ };
109
+ const moduleKeys = Array.isArray(keys)
110
+ ? keys
111
+ : ['nodes', 'keyNodeMap', 'childKeysMaps', 'disabledKeys'];
112
+ const { primaryKey, labelKey, disabledKey, childrenKey } = {
113
+ primaryKey: 'id',
114
+ labelKey: 'name',
115
+ childrenKey: 'children',
116
+ disabledKey: 'disabled',
117
+ ...options
118
+ };
119
+ const [hasNodes, hasCKM, hasKNM, hasDK] = Object.keys(result).map((m) => moduleKeys.includes(m));
120
+ const readTreeData = (nodes, parent) => {
121
+ nodes.forEach((node) => {
122
+ const { [primaryKey]: key, [labelKey]: label, [childrenKey]: children, [disabledKey]: disabled } = node;
123
+ let keyNode = undefined;
124
+ if (hasNodes) {
125
+ result.nodes.push(node);
126
+ }
127
+ if (hasKNM && key !== undefined) {
128
+ keyNode = { keyVlaue: key, keyLabel: label, parent, children: [] };
129
+ parent?.children.push(keyNode);
130
+ result.keyNodeMap[key] = keyNode;
131
+ }
132
+ if (hasDK && disabled && key !== undefined) {
133
+ result.disabledKeys.push(key);
134
+ }
135
+ if (Array.isArray(children) && children.length) {
136
+ if (hasCKM) {
137
+ result.childKeysMaps[key] = children.map((item) => item[primaryKey]);
138
+ }
139
+ readTreeData(children, keyNode);
140
+ }
141
+ });
142
+ };
143
+ treeData && readTreeData(treeData);
144
+ return result;
145
+ }
146
+
147
+ exports.array2tree = array2tree;
148
+ exports.tree2array = tree2array;
149
+ exports.treeAnalyse = treeAnalyse;
@@ -1,4 +1,4 @@
1
- export declare type TimeUnitShort = 'd' | 'h' | 'm' | 's';
1
+ export type TimeUnitShort = 'd' | 'h' | 'm' | 's';
2
2
  export interface DurationDetail {
3
3
  d?: number;
4
4
  h?: number;
@@ -9,7 +9,7 @@ export interface EventPayload<T = any> {
9
9
  /** which emitter can recived the event */
10
10
  targetEmitterName?: string;
11
11
  }
12
- export declare type WatchersMap = Map<string | symbol, Set<AnyFunction>>;
12
+ export type WatchersMap = Map<string | symbol, Set<AnyFunction>>;
13
13
  export interface ConfigOptions {
14
14
  /** the name of current emitter */
15
15
  name?: string;
@@ -30,8 +30,8 @@ export declare const NOMETHOD: unique symbol;
30
30
  */
31
31
  export declare function eventTargetEmitter(options?: ConfigOptions): {
32
32
  name: string | undefined;
33
- rootEventListener: <T = any>(payload: EventPayload<T>) => void;
34
- on: <T_1>(method: string | symbol, listener: (data: T_1) => any, options?: BindOptions) => void;
33
+ rootEventListener: AnyFunction<any>;
34
+ on: <T>(method: string | symbol, listener: (data: T) => any, options?: BindOptions) => void;
35
35
  off: (method: string | symbol, callback?: AnyFunction, options?: BindOptions) => void;
36
36
  emit: (methodOrPayload: string | EventPayload<any>, data?: any, target?: string | undefined) => void;
37
37
  createPayload: (methodOrPayload: string | EventPayload, data?: any, target?: string) => EventPayload<any>;
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v2.0.2
3
- * (c) 2022 wxhccc
2
+ * @wxhccc/es-util v2.1.1
3
+ * (c) 2023 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
package/dist/index.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v2.0.2
3
- * (c) 2022 wxhccc
2
+ * @wxhccc/es-util v2.1.1
3
+ * (c) 2023 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  const { hasOwnProperty, toString } = Object.prototype;
@@ -33,14 +33,31 @@ function array2tree(array, options = {}) {
33
33
  (typeof parentRefKey === 'string' ? parentRefKey : '_parent');
34
34
  const nodeMap = {};
35
35
  const treeNodes = [];
36
- isArr(array) &&
37
- array.forEach((item) => {
38
- !hasOwnProp(nodeMap, item[id]) &&
39
- (nodeMap[item[id]] = Object.assign({}, item, createNode(children)));
40
- hasOwnProp(nodeMap, item[pid]) &&
41
- nodeMap[item[pid]][children].push(Object.assign(nodeMap[item[id]], pRefKey ? { [pRefKey]: nodeMap[item[pid]] } : {}));
42
- !item[pid] && treeNodes.push(nodeMap[item[id]]);
43
- });
36
+ if (isArr(array)) {
37
+ const unsortChildren = [];
38
+ const transform = (items) => {
39
+ items.forEach((item) => {
40
+ if (!hasOwnProp(nodeMap, item[id])) {
41
+ nodeMap[item[id]] = { ...item, ...createNode(children) };
42
+ }
43
+ if (!item[pid]) {
44
+ treeNodes.push(nodeMap[item[id]]);
45
+ }
46
+ else if (hasOwnProp(nodeMap, item[pid])) {
47
+ nodeMap[item[pid]][children].push(Object.assign(nodeMap[item[id]], pRefKey ? { [pRefKey]: nodeMap[item[pid]] } : {}));
48
+ }
49
+ else {
50
+ unsortChildren.push(item);
51
+ }
52
+ });
53
+ };
54
+ transform(array);
55
+ console.log(1111, unsortChildren);
56
+ // 如果有父节点顺序在后的,再循环一次
57
+ if (unsortChildren.length) {
58
+ transform(unsortChildren);
59
+ }
60
+ }
44
61
  if (isFn(createRoot)) {
45
62
  return createRoot(treeNodes);
46
63
  }
@@ -82,6 +99,57 @@ function tree2array(tree, options = {}) {
82
99
  const rootTree = isArr(tree) ? createNode(children, tree) : tree;
83
100
  getNode(rootTree, null, true);
84
101
  return nodes;
102
+ }
103
+ /**
104
+ * 分析id唯一的树节点,得到不同结构的数据
105
+ * @param treeData 树数据
106
+ * @param options 配置项
107
+ * @param keys 可指定的数据类型的key,默认返回完整数据
108
+ * @returns
109
+ */
110
+ function treeAnalyse(treeData, options, keys) {
111
+ const result = {
112
+ nodes: [],
113
+ childKeysMaps: {},
114
+ keyNodeMap: {},
115
+ disabledKeys: []
116
+ };
117
+ const moduleKeys = Array.isArray(keys)
118
+ ? keys
119
+ : ['nodes', 'keyNodeMap', 'childKeysMaps', 'disabledKeys'];
120
+ const { primaryKey, labelKey, disabledKey, childrenKey } = {
121
+ primaryKey: 'id',
122
+ labelKey: 'name',
123
+ childrenKey: 'children',
124
+ disabledKey: 'disabled',
125
+ ...options
126
+ };
127
+ const [hasNodes, hasCKM, hasKNM, hasDK] = Object.keys(result).map((m) => moduleKeys.includes(m));
128
+ const readTreeData = (nodes, parent) => {
129
+ nodes.forEach((node) => {
130
+ const { [primaryKey]: key, [labelKey]: label, [childrenKey]: children, [disabledKey]: disabled } = node;
131
+ let keyNode = undefined;
132
+ if (hasNodes) {
133
+ result.nodes.push(node);
134
+ }
135
+ if (hasKNM && key !== undefined) {
136
+ keyNode = { keyVlaue: key, keyLabel: label, parent, children: [] };
137
+ parent?.children.push(keyNode);
138
+ result.keyNodeMap[key] = keyNode;
139
+ }
140
+ if (hasDK && disabled && key !== undefined) {
141
+ result.disabledKeys.push(key);
142
+ }
143
+ if (Array.isArray(children) && children.length) {
144
+ if (hasCKM) {
145
+ result.childKeysMaps[key] = children.map((item) => item[primaryKey]);
146
+ }
147
+ readTreeData(children, keyNode);
148
+ }
149
+ });
150
+ };
151
+ treeData && readTreeData(treeData);
152
+ return result;
85
153
  }
86
154
 
87
155
  /* 身份证正则 */
@@ -391,7 +459,8 @@ function wrapPromise(promise, options) {
391
459
  let isLocking = false;
392
460
  const stateLock = (bool) => {
393
461
  if (lockRefHandle) {
394
- lockRefHandle[0][lockRefHandle[1]] = bool;
462
+ const [ref, key] = lockRefHandle;
463
+ ref[key] = bool;
395
464
  }
396
465
  if (lockSwitchHook) {
397
466
  lockSwitchHook(bool);
@@ -399,7 +468,7 @@ function wrapPromise(promise, options) {
399
468
  };
400
469
  const checkLock = () => {
401
470
  // use refHandle if state not update sync
402
- return lockRefHandle ? lockRefHandle[0][lockRefHandle[1]] : false;
471
+ return lockRefHandle ? !!lockRefHandle[0][lockRefHandle[1]] : false;
403
472
  };
404
473
  if (lock) {
405
474
  const isRefHandle = (val) => isArr(val) && val.length === 2;
@@ -854,4 +923,4 @@ const secondsToDuration = (number, maxUnit = 'h') => {
854
923
  return result;
855
924
  };
856
925
 
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 };
926
+ 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,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v2.0.2
3
- * (c) 2022 wxhccc
2
+ * @wxhccc/es-util v2.1.1
3
+ * (c) 2023 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
@@ -37,14 +37,31 @@ function array2tree(array, options = {}) {
37
37
  (typeof parentRefKey === 'string' ? parentRefKey : '_parent');
38
38
  const nodeMap = {};
39
39
  const treeNodes = [];
40
- isArr(array) &&
41
- array.forEach((item) => {
42
- !hasOwnProp(nodeMap, item[id]) &&
43
- (nodeMap[item[id]] = Object.assign({}, item, createNode(children)));
44
- hasOwnProp(nodeMap, item[pid]) &&
45
- nodeMap[item[pid]][children].push(Object.assign(nodeMap[item[id]], pRefKey ? { [pRefKey]: nodeMap[item[pid]] } : {}));
46
- !item[pid] && treeNodes.push(nodeMap[item[id]]);
47
- });
40
+ if (isArr(array)) {
41
+ const unsortChildren = [];
42
+ const transform = (items) => {
43
+ items.forEach((item) => {
44
+ if (!hasOwnProp(nodeMap, item[id])) {
45
+ nodeMap[item[id]] = { ...item, ...createNode(children) };
46
+ }
47
+ if (!item[pid]) {
48
+ treeNodes.push(nodeMap[item[id]]);
49
+ }
50
+ else if (hasOwnProp(nodeMap, item[pid])) {
51
+ nodeMap[item[pid]][children].push(Object.assign(nodeMap[item[id]], pRefKey ? { [pRefKey]: nodeMap[item[pid]] } : {}));
52
+ }
53
+ else {
54
+ unsortChildren.push(item);
55
+ }
56
+ });
57
+ };
58
+ transform(array);
59
+ console.log(1111, unsortChildren);
60
+ // 如果有父节点顺序在后的,再循环一次
61
+ if (unsortChildren.length) {
62
+ transform(unsortChildren);
63
+ }
64
+ }
48
65
  if (isFn(createRoot)) {
49
66
  return createRoot(treeNodes);
50
67
  }
@@ -86,6 +103,57 @@ function tree2array(tree, options = {}) {
86
103
  const rootTree = isArr(tree) ? createNode(children, tree) : tree;
87
104
  getNode(rootTree, null, true);
88
105
  return nodes;
106
+ }
107
+ /**
108
+ * 分析id唯一的树节点,得到不同结构的数据
109
+ * @param treeData 树数据
110
+ * @param options 配置项
111
+ * @param keys 可指定的数据类型的key,默认返回完整数据
112
+ * @returns
113
+ */
114
+ function treeAnalyse(treeData, options, keys) {
115
+ const result = {
116
+ nodes: [],
117
+ childKeysMaps: {},
118
+ keyNodeMap: {},
119
+ disabledKeys: []
120
+ };
121
+ const moduleKeys = Array.isArray(keys)
122
+ ? keys
123
+ : ['nodes', 'keyNodeMap', 'childKeysMaps', 'disabledKeys'];
124
+ const { primaryKey, labelKey, disabledKey, childrenKey } = {
125
+ primaryKey: 'id',
126
+ labelKey: 'name',
127
+ childrenKey: 'children',
128
+ disabledKey: 'disabled',
129
+ ...options
130
+ };
131
+ const [hasNodes, hasCKM, hasKNM, hasDK] = Object.keys(result).map((m) => moduleKeys.includes(m));
132
+ const readTreeData = (nodes, parent) => {
133
+ nodes.forEach((node) => {
134
+ const { [primaryKey]: key, [labelKey]: label, [childrenKey]: children, [disabledKey]: disabled } = node;
135
+ let keyNode = undefined;
136
+ if (hasNodes) {
137
+ result.nodes.push(node);
138
+ }
139
+ if (hasKNM && key !== undefined) {
140
+ keyNode = { keyVlaue: key, keyLabel: label, parent, children: [] };
141
+ parent?.children.push(keyNode);
142
+ result.keyNodeMap[key] = keyNode;
143
+ }
144
+ if (hasDK && disabled && key !== undefined) {
145
+ result.disabledKeys.push(key);
146
+ }
147
+ if (Array.isArray(children) && children.length) {
148
+ if (hasCKM) {
149
+ result.childKeysMaps[key] = children.map((item) => item[primaryKey]);
150
+ }
151
+ readTreeData(children, keyNode);
152
+ }
153
+ });
154
+ };
155
+ treeData && readTreeData(treeData);
156
+ return result;
89
157
  }
90
158
 
91
159
  /* 身份证正则 */
@@ -395,7 +463,8 @@ function wrapPromise(promise, options) {
395
463
  let isLocking = false;
396
464
  const stateLock = (bool) => {
397
465
  if (lockRefHandle) {
398
- lockRefHandle[0][lockRefHandle[1]] = bool;
466
+ const [ref, key] = lockRefHandle;
467
+ ref[key] = bool;
399
468
  }
400
469
  if (lockSwitchHook) {
401
470
  lockSwitchHook(bool);
@@ -403,7 +472,7 @@ function wrapPromise(promise, options) {
403
472
  };
404
473
  const checkLock = () => {
405
474
  // use refHandle if state not update sync
406
- return lockRefHandle ? lockRefHandle[0][lockRefHandle[1]] : false;
475
+ return lockRefHandle ? !!lockRefHandle[0][lockRefHandle[1]] : false;
407
476
  };
408
477
  if (lock) {
409
478
  const isRefHandle = (val) => isArr(val) && val.length === 2;
@@ -881,4 +950,5 @@ exports.safeJsonParse = safeJsonParse;
881
950
  exports.secondsToDuration = secondsToDuration;
882
951
  exports.switchNullToUndefined = switchNullToUndefined;
883
952
  exports.tree2array = tree2array;
953
+ exports.treeAnalyse = treeAnalyse;
884
954
  exports.wp = wp;
package/dist/index.min.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v2.0.2
3
- * (c) 2022 wxhccc
2
+ * @wxhccc/es-util v2.1.1
3
+ * (c) 2023 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,i=Array.isArray,s=e=>{const t=(r=e,n.call(r)).match(/^\[object (.*)\]$/);var r;return t?t[1]:""},a=e=>"Object"===s(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:s}={...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=>i(e)&&2===e.length;e(r)?c=r:o(r)&&(a=r,e(s)&&(c=s)),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?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 s=Object.keys(t),a={},c={};r(e,(t=>{s.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],s=t[n];if(!r||!s)return e;if("join"===s||"pop"===s)i(r)&&r.length&&(e[n]="join"===s?r.join(","):r.slice(-1)[0]);else if(2===s.length||3===s.length){if(!r||2!==r.length)return e;const[t,n,i]=s,[a,c]=r;Object.assign(e,{[t]:o(d)?d(a,i):a,[n]:o(d)?d(c,i):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||{},i=o(r)?r(t):null,s=/\|-[a-z]+-\|/,a=(e,...t)=>{try{e(...t)}catch(e){console.error(e)}},c=o(i)?i:e=>{const{method:r,data:o,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(s);r&&i&&r!==i||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 i=l(e,r);n?t.get(i)?.delete(n):t.delete(i)},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(s)))),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,i=0,s=0;for(let t=0;t<17;t++)i=parseInt(e[t]),s=n[t],o+=i*s;return r[o%11].toString()===e[17]}return!0})()},e.NOMETHOD=x,e.array2tree=function(e,t={}){const{primaryKey:n,parentKey:r,childrenKey:s,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 i(e)&&e.forEach((e=>{!c(f,e[n])&&(f[e[n]]=Object.assign({},e,l(s))),c(f,e[r])&&f[e[r]][s].push(Object.assign(f[e[n]],d?{[d]:f[e[r]]}:{})),!e[r]&&p.push(f[e[n]])})),o(a)?a(p):a?{[s]: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:s,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(s);let p="",m=0;if(i(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)?i(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,i=0,s=0,a=[],c=!1;const l=e=>{const n=e-(s||e);s=e,i+=n,c&&(a=a.filter((e=>!e.needClear)),c=!1),!t||a.length?(a.forEach((e=>{const{callback:t,maxTime:r,runTime:o,elapsed:s,interval:a,needClear:l}=e;if(!l){if(r&&o>=r)return e.needClear=!0,void(c=!0);if(s>=a){try{t(i)}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})()&&(!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,o)=>{const i="string"==typeof t?e[t]:t(e,o),s="string"==typeof n?e[n]:n(e,o);["string","number"].includes(typeof i)&&(r[i]=s)})),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:i,startFrom:s,endUntil:a}={maskWith:"*",...n,...t};let c=e,l="",u="";const f=s?e.indexOf(s):-1;if(f>-1){const t=f+s.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!==i?i>=0?i:y+i: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:i,createPayload:s,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 window.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:i,send:(...e)=>{const t=s(...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:s,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,u=!1){const d=s?{}:{[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)}i(t[o])&&t[o].length&&t[o].forEach((r=>e(r,t[n])))}(i(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,o=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 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:i}={...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=>o(e)&&2===e.length;e(r)?c=r:s(r)&&(a=r,e(i)&&(c=i)),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?o(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(o(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:d,dateFormat:u}={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)o(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,o]=i,[a,c]=r;Object.assign(e,{[t]:s(u)?u(a,o):a,[n]:s(u)?u(c,o):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||{},o=s(r)?r(t):null,i=/\|-[a-z]+-\|/,a=(e,...t)=>{try{e(...t)}catch(e){console.error(e)}},c=s(o)?o:e=>{const{method:r,data:s,originEmitterName:o,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&&o&&r!==o||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);const o=t.get(s);o?.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 o=l(e,r);n?t.get(o)?.delete(n):t.delete(o)},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(i)))),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,o=0,i=0;for(let t=0;t<17;t++)o=parseInt(e[t]),i=n[t],s+=o*i;return r[s%11].toString()===e[17]}return!0})()},e.NOMETHOD=j,e.array2tree=function(e,t={}){const{primaryKey:n,parentKey:r,childrenKey:i,createRoot:a,parentRefKey:d}={primaryKey:"id",parentKey:"pid",childrenKey:"children",createRoot:!1,parentRefKey:!1,...t},u=d&&("string"==typeof d?d:"_parent"),f={},p=[];if(o(e)){const t=[],s=e=>{e.forEach((e=>{c(f,e[n])||(f[e[n]]={...e,...l(i)}),e[r]?c(f,e[r])?f[e[r]][i].push(Object.assign(f[e[n]],u?{[u]:f[e[r]]}:{})):t.push(e):p.push(f[e[n]])}))};s(e),console.log(1111,t),t.length&&s(t)}return s(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:s,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: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(i);let p="",m=0;if(o(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)?o(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,o=0,i=0,a=[],c=!1;const l=e=>{const n=e-(i||e);i=e,o+=n,c&&(a=a.filter((e=>!e.needClear)),c=!1),!t||a.length?(a.forEach((e=>{const{callback:t,maxTime:r,runTime:s,elapsed:i,interval:a,needClear:l}=e;if(!l){if(r&&s>=r)return e.needClear=!0,void(c=!0);if(i>=a){try{t(o)}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})()&&(!o(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 o(e)&&t&&n&&[t,n].every((e=>["string","function"].includes(typeof e)))&&e.forEach(((e,s)=>{const o="string"==typeof t?e[t]:t(e,s),i="string"==typeof n?e[n]:n(e,s);["string","number"].includes(typeof o)&&(r[o]=i)})),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:o,startFrom:i,endUntil:a}={maskWith:"*",...n,...t};let c=e,l="",d="";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),d=e.slice(p));const m=c.split(""),h=[l],y=m.length,g=[s>=0?s:y+s,void 0!==o?o>=0?o:y+o: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:o,createPayload:i,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:o,send:(...e)=>{const t=i(...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:i,returnObject:a}=Object.assign({hasParentKey:!0,primaryKey:"id",parentKey:"pid",childrenKey:"children",returnObject:!1},t),c=a?{}:[];return o(e)||"object"==typeof e?(function e(t,l,d=!1){const u=i?{}:{[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)}o(t[s])&&t[s].length&&t[s].forEach((r=>e(r,t[n])))}(o(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:o,labelKey:i,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{[o]:n,[i]: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[o]))),p(m,y))}))};return e&&p(e),r},e.wp=p,Object.defineProperty(e,"__esModule",{value:!0})}));
@@ -10,7 +10,7 @@ interface PropHandler {
10
10
  (item: any, index: number): string;
11
11
  }
12
12
  export declare function mapToObject(objectArray: AnyObject[], keyProp?: string | PropHandler, valueProp?: string | PropHandler): Record<string, string | number>;
13
- declare type MergeFn = <T>(...args: T[]) => T;
13
+ type MergeFn = <T>(...args: T[]) => T;
14
14
  /**
15
15
  * checkout values form object as an array
16
16
  * 从对象中挑选指定的值并以数组形式返回,必要时可使用自定义属性覆盖选中对象
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v2.0.2
3
- * (c) 2022 wxhccc
2
+ * @wxhccc/es-util v2.1.1
3
+ * (c) 2023 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
@@ -1,4 +1,4 @@
1
- declare type AnyObject = Record<string | number, any>;
1
+ type AnyObject = Record<string | number, any>;
2
2
  /**
3
3
  * JSON.parse string safely
4
4
  * @param json string
@@ -28,8 +28,8 @@ export declare const switchNullToUndefined: (data: any) => any;
28
28
  * 参数转换规则的配置对象
29
29
  * 值可以是时间范围转换所需的开始,结束时间字段的名称,或者需要进行拼接的数组
30
30
  */
31
- export declare type ParamsSwitchMaps<DK extends string = string, RK extends string = string> = Record<DK, [RK, RK] | [RK, RK, string] | 'join' | 'pop'>;
32
- export declare type DateFormat = (date: any, format?: string) => string;
31
+ export type ParamsSwitchMaps<DK extends string = string, RK extends string = string> = Record<DK, [RK, RK] | [RK, RK, string] | 'join' | 'pop'>;
32
+ export type DateFormat = (date: any, format?: string) => string;
33
33
  /**
34
34
  * 将搜素条件里的数组字段转换为其他格式,通常用于搜索表单的字段转换
35
35
  * @param formData 传入参数
package/dist/optional.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v2.0.2
3
- * (c) 2022 wxhccc
2
+ * @wxhccc/es-util v2.1.1
3
+ * (c) 2023 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
@@ -23,5 +23,5 @@ export declare function pageCommunicate(options?: PcConfigOptions): {
23
23
  send: (methodOrPayload: string | OrgEventPayload<any>, data?: any, target?: string | undefined) => void;
24
24
  destory: () => void;
25
25
  };
26
- export declare type BccnInstance = ReturnType<typeof pageCommunicate>;
26
+ export type BccnInstance = ReturnType<typeof pageCommunicate>;
27
27
  export default pageCommunicate;
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v2.0.2
3
- * (c) 2022 wxhccc
2
+ * @wxhccc/es-util v2.1.1
3
+ * (c) 2023 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
package/dist/promise.d.ts CHANGED
@@ -4,36 +4,37 @@
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
- /** 防止多次promise函数运行控制器,对于响应式系统,可以同时用作BoolSwitch */
8
- export declare type LockRefHandle<T extends {
7
+ export type BoolRef = {
9
8
  [key: string]: boolean;
10
- } = Record<string, boolean>> = [T, string];
9
+ };
10
+ /** 防止多次promise函数运行控制器,对于响应式系统,可以同时用作BoolSwitch */
11
+ export type LockRefHandle<T = BoolRef> = [T, keyof T];
11
12
  /** loading等状态的切换函数 */
12
- export declare type BoolSwitch = (val: boolean) => unknown;
13
+ export type BoolSwitch = (val: boolean) => unknown;
13
14
  /**
14
15
  * wrap promise with lock, support reactive environment like react or vue
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
- declare type WpReturn<T> = Promise<T | undefined>;
27
- declare type WpArrReturn<T> = Promise<[null, T] | [Error, undefined]>;
28
- declare type WpMayLockArrReturn<T> = Promise<[null, T] | [Error, undefined]>;
29
- declare type WpPromise<T> = Promise<T> | (() => Promise<T>);
30
- declare function wrapPromise<T>(promise: WpPromise<T>, options?: WpOptions & {
27
+ type WpReturn<T> = Promise<T | undefined>;
28
+ type WpArrReturn<T> = Promise<[null, T] | [Error, undefined]>;
29
+ type WpMayLockArrReturn<T> = Promise<[null, T] | [Error, undefined]>;
30
+ type WpPromise<T> = Promise<T> | (() => Promise<T>);
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,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v2.0.2
3
- * (c) 2022 wxhccc
2
+ * @wxhccc/es-util v2.1.1
3
+ * (c) 2023 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
@@ -31,7 +31,8 @@ function wrapPromise(promise, options) {
31
31
  let isLocking = false;
32
32
  const stateLock = (bool) => {
33
33
  if (lockRefHandle) {
34
- lockRefHandle[0][lockRefHandle[1]] = bool;
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;
@@ -12,7 +12,7 @@ interface TaskItem {
12
12
  /** 当前任务是否需要在下个循环周期时清除,内部变量 */
13
13
  needClear?: boolean;
14
14
  }
15
- export declare type TimerCallback = TaskItem['callback'];
15
+ export type TimerCallback = TaskItem['callback'];
16
16
  export interface RAFTimerOptions {
17
17
  /** 无任务时是否自动停止,停止后需要手动启动 */
18
18
  autoStopWhenNoTask?: boolean;
@@ -32,5 +32,5 @@ export declare const createRAFTimer: (options?: RAFTimerOptions) => {
32
32
  isPaused: () => boolean;
33
33
  };
34
34
  /** 计时器实例 */
35
- export declare type TimerInstance = ReturnType<typeof createRAFTimer>;
35
+ export type TimerInstance = ReturnType<typeof createRAFTimer>;
36
36
  export {};
package/dist/raf-timer.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v2.0.2
3
- * (c) 2022 wxhccc
2
+ * @wxhccc/es-util v2.1.1
3
+ * (c) 2023 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
package/dist/types.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- export declare type AnyObject = {
1
+ export type AnyObject = {
2
2
  [key: string]: any;
3
3
  };
4
- export declare type AnyFunction<T = any> = (...args: any[]) => T;
4
+ export type AnyFunction<T = any> = (...args: any[]) => T;
5
+ export type StrOrNum = string | number;
package/dist/utils.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v2.0.2
3
- * (c) 2022 wxhccc
2
+ * @wxhccc/es-util v2.1.1
3
+ * (c) 2023 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
package/dist/validate.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v2.0.2
3
- * (c) 2022 wxhccc
2
+ * @wxhccc/es-util v2.1.1
3
+ * (c) 2023 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
@@ -4,7 +4,7 @@ interface Options {
4
4
  precision?: number;
5
5
  detail?: boolean;
6
6
  }
7
- declare type StrOrNum = number | string;
7
+ type StrOrNum = number | string;
8
8
  export declare function byteStringify(byteNum: StrOrNum, options?: Options & {
9
9
  detail?: false;
10
10
  }): string;
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v2.0.2
3
- * (c) 2022 wxhccc
2
+ * @wxhccc/es-util v2.1.1
3
+ * (c) 2023 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wxhccc/es-util",
3
- "version": "2.0.2",
3
+ "version": "2.1.1",
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",