@wxhccc/es-util 1.6.0 → 2.0.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.
Files changed (39) hide show
  1. package/LICENSE +20 -20
  2. package/README.md +286 -57
  3. package/dist/array-tree-switch.d.ts +18 -2
  4. package/dist/date-time.d.ts +14 -0
  5. package/dist/event-target-emitter.d.ts +45 -0
  6. package/dist/event-target-emitter.js +147 -0
  7. package/dist/index.d.ts +4 -0
  8. package/dist/index.esm.js +499 -216
  9. package/dist/index.js +505 -218
  10. package/dist/index.min.js +2 -2
  11. package/dist/object-array.d.ts +7 -9
  12. package/dist/object-array.js +34 -16
  13. package/dist/optional.d.ts +6 -9
  14. package/dist/optional.js +136 -0
  15. package/dist/page-communicate.d.ts +27 -0
  16. package/dist/page-communicate.js +66 -0
  17. package/dist/promise.d.ts +21 -24
  18. package/dist/promise.js +24 -132
  19. package/dist/raf-timer.d.ts +36 -0
  20. package/dist/raf-timer.js +103 -0
  21. package/dist/types.d.ts +4 -0
  22. package/dist/utils.d.ts +10 -0
  23. package/dist/utils.js +30 -0
  24. package/dist/validate.js +54 -6
  25. package/dist/value-string-switch/byte-string.d.ts +9 -4
  26. package/dist/value-string-switch/index.d.ts +1 -0
  27. package/dist/value-string-switch/mask-data.d.ts +1 -2
  28. package/dist/value-string-switch/uri-b64.d.ts +8 -0
  29. package/dist/value-string-switch.js +28 -11
  30. package/package.json +19 -19
  31. package/types/array-tree-switch.d.ts +0 -49
  32. package/types/index.d.ts +0 -6
  33. package/types/object-array.d.ts +0 -33
  34. package/types/optional.d.ts +0 -50
  35. package/types/promise.d.ts +0 -44
  36. package/types/validate.d.ts +0 -2
  37. package/types/value-string-switch/byte-string.d.ts +0 -12
  38. package/types/value-string-switch/index.d.ts +0 -2
  39. package/types/value-string-switch/mask-data.d.ts +0 -22
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.6.0
2
+ * @wxhccc/es-util v2.0.1
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -7,37 +7,45 @@
7
7
 
8
8
  Object.defineProperty(exports, '__esModule', { value: true });
9
9
 
10
- const { hasOwnProperty: hasOwnProperty$1 } = Object.prototype;
10
+ const { hasOwnProperty, toString } = Object.prototype;
11
+ const objForEch = (obj, callbackfn) => {
12
+ Object.keys(obj).forEach((key, index) => callbackfn(key, obj[key], index));
13
+ };
14
+ const isFn = (fn) => typeof fn === 'function';
15
+ const isArr = Array.isArray;
16
+ const objToString = (obj) => toString.call(obj);
17
+ const objType = (val) => {
18
+ const typeKeys = objToString(val).match(/^\[object (.*)\]$/);
19
+ return typeKeys ? typeKeys[1] : '';
20
+ };
21
+ const isObj = (obj) => objType(obj) === 'Object';
22
+ const hasOwnProp = (obj, v) => hasOwnProperty.call(obj, v);
23
+
11
24
  function createNode(children, value = []) {
12
25
  return { [children]: value };
13
26
  }
14
- /**
15
- * translate array to tree
16
- * @param {Array} array the node array need to be translate
17
- * @param {Object} options the options
18
- * @param {string} primaryKey the primary key of node
19
- * @param {string} parentKey the parent's key of node
20
- * @param {string} childrenKey the child's key of node
21
- * @param {boolean | Function} createNode whether create root node, or function which can return root node
22
- * @param {boolean | string} parentRefKey parent reference key of node
23
- */
24
27
  function array2tree(array, options = {}) {
25
- const { primaryKey: id, parentKey: pid, childrenKey: children, createRoot, parentRefKey } = Object.assign({
28
+ const { primaryKey: id, parentKey: pid, childrenKey: children, createRoot, parentRefKey } = {
26
29
  primaryKey: 'id',
27
30
  parentKey: 'pid',
28
31
  childrenKey: 'children',
29
32
  createRoot: false,
30
- parentRefKey: false
31
- }, options);
32
- const pRefKey = parentRefKey && (typeof parentRefKey === 'string' ? parentRefKey : '_parent');
33
- let nodeMap = {};
34
- let treeNodes = [];
35
- Array.isArray(array) && array.forEach(item => {
36
- !hasOwnProperty$1.call(nodeMap, item[id]) && (nodeMap[item[id]] = Object.assign({}, item, createNode(children)));
37
- hasOwnProperty$1.call(nodeMap, item[pid]) && nodeMap[item[pid]][children].push(Object.assign(nodeMap[item[id]], pRefKey ? { [pRefKey]: nodeMap[item[pid]] } : {}));
38
- !item[pid] && treeNodes.push(nodeMap[item[id]]);
39
- });
40
- if (typeof createRoot === 'function') {
33
+ parentRefKey: false,
34
+ ...options
35
+ };
36
+ const pRefKey = parentRefKey &&
37
+ (typeof parentRefKey === 'string' ? parentRefKey : '_parent');
38
+ const nodeMap = {};
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
+ });
48
+ if (isFn(createRoot)) {
41
49
  return createRoot(treeNodes);
42
50
  }
43
51
  else if (createRoot) {
@@ -46,22 +54,12 @@ function array2tree(array, options = {}) {
46
54
  return treeNodes;
47
55
  }
48
56
  function nodeChildFilter(node, childrenKey) {
49
- let newNode = {};
50
- for (let i in node) {
57
+ const newNode = {};
58
+ for (const i in node) {
51
59
  i !== childrenKey && (newNode[i] = node[i]);
52
60
  }
53
61
  return newNode;
54
62
  }
55
- /**
56
- * translate tree to array
57
- * @param {Array/Object} tree the node tree need to be translate
58
- * @param {Object} options the options
59
- * @param {string} primaryKey the primary key of tree node
60
- * @param {string} parentKey the parent's key of tree node
61
- * @param {string} childrenKey the child's key of tree node
62
- * @param {boolean} hasParentKey whether create parent id in node
63
- * @param {boolean} returnObject whether return object or array
64
- */
65
63
  function tree2array(tree, options = {}) {
66
64
  const { primaryKey: id, parentKey: pid, childrenKey: children, hasParentKey, returnObject } = Object.assign({
67
65
  hasParentKey: true,
@@ -70,20 +68,22 @@ function tree2array(tree, options = {}) {
70
68
  childrenKey: 'children',
71
69
  returnObject: false
72
70
  }, options);
73
- let nodes = returnObject ? {} : [];
74
- if (!Array.isArray(tree) && typeof tree !== 'object')
71
+ const nodes = returnObject ? {} : [];
72
+ if (!isArr(tree) && typeof tree !== 'object')
75
73
  return nodes;
76
74
  function getNode(node, parentId, root = false) {
77
- let baseNode = hasParentKey ? {} : { [pid]: parentId };
75
+ const baseNode = hasParentKey ? {} : { [pid]: parentId };
78
76
  if (!root) {
79
77
  const newNode = Object.assign(baseNode, nodeChildFilter(node, children));
80
- returnObject ? (nodes[node[id]] = newNode) : nodes.push(newNode);
78
+ returnObject
79
+ ? (nodes[node[id]] = newNode)
80
+ : nodes.push(newNode);
81
81
  }
82
- if (Array.isArray(node[children]) && node[children].length) {
82
+ if (isArr(node[children]) && node[children].length) {
83
83
  node[children].forEach((childNode) => getNode(childNode, node[id]));
84
84
  }
85
85
  }
86
- const rootTree = Array.isArray(tree) ? createNode(children, tree) : tree;
86
+ const rootTree = isArr(tree) ? createNode(children, tree) : tree;
87
87
  getNode(rootTree, null, true);
88
88
  return nodes;
89
89
  }
@@ -93,7 +93,43 @@ const idCardReg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{
93
93
  /* 身份证合法性验证 */
94
94
  function ChinaIdCardValid(idNo) {
95
95
  const idNumber = idNo.toString().toUpperCase();
96
- const provCodes = ['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'];
96
+ const provCodes = [
97
+ '11',
98
+ '12',
99
+ '13',
100
+ '14',
101
+ '15',
102
+ '21',
103
+ '22',
104
+ '23',
105
+ '31',
106
+ '32',
107
+ '33',
108
+ '34',
109
+ '35',
110
+ '36',
111
+ '37',
112
+ '41',
113
+ '42',
114
+ '43',
115
+ '44',
116
+ '45',
117
+ '46',
118
+ '50',
119
+ '51',
120
+ '52',
121
+ '53',
122
+ '54',
123
+ '61',
124
+ '62',
125
+ '63',
126
+ '64',
127
+ '65',
128
+ '71',
129
+ '81',
130
+ '82',
131
+ '91'
132
+ ];
97
133
  const lastCodeCheck = () => {
98
134
  if (idNumber.length === 18) {
99
135
  const chars = idNumber.split('');
@@ -115,7 +151,9 @@ function ChinaIdCardValid(idNo) {
115
151
  }
116
152
  return true;
117
153
  };
118
- return idCardReg.test(idNumber) && provCodes.includes(idNumber.substr(0, 2)) && lastCodeCheck();
154
+ return (idCardReg.test(idNumber) &&
155
+ provCodes.includes(idNumber.substr(0, 2)) &&
156
+ lastCodeCheck());
119
157
  }
120
158
  // 公式验证函数
121
159
  function formulaValidate(string, variables) {
@@ -127,7 +165,8 @@ function formulaValidate(string, variables) {
127
165
  const bns = /[^+\-*/]\(/; // 错误情况,(前面不是运算符
128
166
  const blns = /\)[^+\-*/]/; // 错误情况,)后面不是运算符
129
167
  const bmatch = () => {
130
- let stack = [];
168
+ // 错误情况,括号不配对
169
+ const stack = [];
131
170
  for (let i = 0, item; i < string.length; i++) {
132
171
  item = string.charAt(i);
133
172
  if (item === '(') {
@@ -148,32 +187,54 @@ function formulaValidate(string, variables) {
148
187
  const varInList = (vars) => {
149
188
  const tmpStr = string.replace(/[()+\-*/]{1,}/g, '`');
150
189
  const array = tmpStr.split('`');
151
- return array.every(item => (!/[A-Z]/i.test(item) || vars.includes(item)));
190
+ return array.every((item) => !/[A-Z]/i.test(item) || vars.includes(item));
152
191
  };
153
- return !sc.test(string) && !eb.test(string) && !sl.test(string) && !bs.test(string) && !bns.test(string) && !blns.test(string) && bmatch() && (!Array.isArray(variables) || varInList(variables));
192
+ return (!sc.test(string) &&
193
+ !eb.test(string) &&
194
+ !sl.test(string) &&
195
+ !bs.test(string) &&
196
+ !bns.test(string) &&
197
+ !blns.test(string) &&
198
+ bmatch() &&
199
+ (!isArr(variables) || varInList(variables)));
154
200
  }
155
201
 
156
202
  function mapToObject(objectArray, keyProp = 'key', valueProp = 'value') {
157
- let result = {};
158
- Array.isArray(objectArray) && keyProp && valueProp
159
- && [keyProp, valueProp].every(val => ['string', 'function'].includes(typeof val))
160
- && objectArray.forEach((item, index) => {
203
+ const result = {};
204
+ isArr(objectArray) &&
205
+ keyProp &&
206
+ valueProp &&
207
+ [keyProp, valueProp].every((val) => ['string', 'function'].includes(typeof val)) &&
208
+ objectArray.forEach((item, index) => {
161
209
  const key = typeof keyProp === 'string' ? item[keyProp] : keyProp(item, index);
162
210
  const value = typeof valueProp === 'string' ? item[valueProp] : valueProp(item, index);
163
211
  ['string', 'number'].includes(typeof key) && (result[key] = value);
164
212
  });
165
213
  return result;
166
214
  }
215
+ /**
216
+ * checkout values form object as an array
217
+ * 从对象中挑选指定的值并以数组形式返回,必要时可使用自定义属性覆盖选中对象
218
+ * @param {Object} object
219
+ * @param {string[] | Object} keys
220
+ * @param {string} valueProp
221
+ */
167
222
  function checkoutBy(object, keys, mergeFn) {
168
- if (!(object instanceof Object))
223
+ if (!isObj(object)) {
169
224
  return [];
170
- if (Array.isArray(keys)) {
171
- return keys.map(item => (object[item]));
172
225
  }
173
- else if (keys && keys instanceof Object) {
174
- return Object.keys(keys).map(item => (object[item] instanceof Object && keys[item] instanceof Object)
175
- ? (mergeFn ? mergeFn({}, object[item], keys[item]) : Object.assign({}, object[item], keys[item]))
176
- : (keys[item] || object[item]));
226
+ if (isArr(keys)) {
227
+ return keys.map((key) => object[key]);
228
+ }
229
+ else if (keys && isObj(keys)) {
230
+ return Object.keys(keys).map((key) => {
231
+ const value = keys[key];
232
+ return isObj(object[key]) && isObj(value)
233
+ ? mergeFn
234
+ ? mergeFn({}, object[key], value)
235
+ : Object.assign({}, object[key], value)
236
+ : value || object[key];
237
+ });
177
238
  }
178
239
  return Object.values(object);
179
240
  }
@@ -184,11 +245,12 @@ function checkoutBy(object, keys, mergeFn) {
184
245
  * @param {Object} keysMap
185
246
  */
186
247
  function pickRenameKeys(object, keysMap) {
187
- if (!object || !(object instanceof Object) || !keysMap || !(keysMap instanceof Object))
248
+ if (!object || !isObj(object) || !keysMap || !isObj(keysMap)) {
188
249
  return;
189
- let result = {};
190
- for (let i in object) {
191
- (i in keysMap) && (result[keysMap[i]] = object[i]);
250
+ }
251
+ const result = {};
252
+ for (const i in object) {
253
+ i in keysMap && (result[keysMap[i]] = object[i]);
192
254
  }
193
255
  return result;
194
256
  }
@@ -206,13 +268,16 @@ const configCreater = (standard, unit) => {
206
268
  Z: { expMax: 7, units: { metric: 'ZB', iec: 'ZiB', jedec: 'ZB' } },
207
269
  Y: { expMax: 8, units: { metric: 'YB', iec: 'YiB', jedec: 'YB' } }
208
270
  };
209
- const standBase = { metric: 1000, iec: 1024, jedec: 1024 };
271
+ const standBase = {
272
+ metric: 1000,
273
+ iec: 1024,
274
+ jedec: 1024
275
+ };
210
276
  return {
211
277
  base: standBase[standard] || standBase['jedec'],
212
278
  unitMap: unitMap[unit] || Object.values(unitMap)
213
279
  };
214
280
  };
215
- // translate byte num to string
216
281
  function byteStringify(byteNum, options) {
217
282
  const opts = Object.assign({
218
283
  standard: 'jedec',
@@ -230,14 +295,14 @@ function byteStringify(byteNum, options) {
230
295
  const getValue = (value) => Number.isInteger(value) ? value : value.toFixed(precision);
231
296
  let resUnit = '';
232
297
  let resValue = 0;
233
- if (!Array.isArray(unitMap)) {
298
+ if (!isArr(unitMap)) {
234
299
  const maxValue = Math.pow(base, unitMap.expMax);
235
300
  resUnit = unitMap.units[standard];
236
301
  const value = byteNumber / maxValue;
237
302
  resValue = getValue(value * negative);
238
303
  }
239
304
  else {
240
- unitMap.some(item => {
305
+ unitMap.some((item) => {
241
306
  const maxValue = Math.pow(base, item.expMax);
242
307
  const value = byteNumber / maxValue;
243
308
  if (value > base)
@@ -248,9 +313,6 @@ function byteStringify(byteNum, options) {
248
313
  });
249
314
  }
250
315
  return detail ? { value: resValue, unit: resUnit } : `${resValue} ${resUnit}`;
251
- }
252
- // translate string to byte num
253
- function byteParse(byteStr, options = {}) {
254
316
  }
255
317
 
256
318
  const modeIndexs = {
@@ -267,7 +329,9 @@ function maskData(data, options) {
267
329
  if (typeof data !== 'string' || !data) {
268
330
  return '';
269
331
  }
270
- const modeOpts = options && options.mode && modeIndexs[options.mode] ? modeIndexs[options.mode] : {};
332
+ const modeOpts = options && options.mode && modeIndexs[options.mode]
333
+ ? modeIndexs[options.mode]
334
+ : {};
271
335
  const { maskWith, startCharIndex: start = 0, endCharIndex: end, startFrom, endUntil } = { maskWith: '*', ...modeOpts, ...options };
272
336
  let handleData = data;
273
337
  let beforeChars = '';
@@ -286,7 +350,10 @@ function maskData(data, options) {
286
350
  const chars = handleData.split('');
287
351
  const newChars = [beforeChars];
288
352
  const charLen = chars.length;
289
- const indexs = [start >= 0 ? start : charLen + start, end !== undefined ? (end >= 0 ? end : charLen + end) : charLen - 1];
353
+ const indexs = [
354
+ start >= 0 ? start : charLen + start,
355
+ end !== undefined ? (end >= 0 ? end : charLen + end) : charLen - 1
356
+ ];
290
357
  let [startIdx, endIdx] = indexs;
291
358
  endIdx = endIdx > 0 && endIdx < charLen ? endIdx : charLen - 1;
292
359
  startIdx = startIdx >= 0 && startIdx <= endIdx ? startIdx : 0;
@@ -297,11 +364,15 @@ function maskData(data, options) {
297
364
  return newChars.join('');
298
365
  }
299
366
 
300
- const { hasOwnProperty, toString: toString$1 } = Object.prototype;
301
- const objType = (val) => {
302
- const typeKeys = toString$1.call(val).match(/^\[object (.*)\]$/);
303
- return typeKeys ? typeKeys[1] : '';
304
- };
367
+ /**
368
+ * 将字符串编码为base64, 采用encodeURIComponent+window.btoa,主要为了解决atob/btoa处理特殊字符会报错的问题,性能不如buffer方案,适用于简单场景
369
+ * @param str 待转换的字符串
370
+ * @returns
371
+ */
372
+ const b64UriEncode = (str) => window.btoa(encodeURIComponent(str));
373
+ /** b64UriEncode对应的解码函数 */
374
+ const b64UriDecode = (str) => decodeURIComponent(window.atob(str));
375
+
305
376
  /**
306
377
  * wrap promise and handle reject or err by return an array like [error, undefined]
307
378
  * @param promise promise
@@ -316,158 +387,55 @@ async function awaitWrapper(promise) {
316
387
  return [err, undefined];
317
388
  }
318
389
  }
319
- function checkContext(context) {
320
- if (!context)
321
- return 'unknown';
322
- if (context._isVue || (context.$ && context.$.vnode)) {
323
- return 'vue';
324
- }
325
- else if ('setState' in context) {
326
- return 'react';
327
- }
328
- return 'unknown';
329
- }
330
- const emptyPromise = () => {
331
- const ep = Promise.resolve(undefined);
332
- return Object.assign(ep, {
333
- then(...args) {
334
- const [onfulfilled] = args;
335
- // if then has be called by Promise.all, let ite pass
336
- if (args.length === 2 && typeof onfulfilled === 'function') {
337
- return onfulfilled(undefined);
338
- }
339
- return ep;
340
- },
341
- catch: (onrejected) => ep,
342
- finally: () => ep
343
- });
344
- };
345
- const lockCtx = {};
346
- function wrapPromise(promise, wrapOrOptions) {
347
- const contextType = checkContext(this);
348
- const isReactiveIns = contextType !== 'unknown';
349
- const context = isReactiveIns ? this : lockCtx;
350
- const stateKey = contextType === 'react' ? 'state' : '';
351
- const contextState = stateKey ? context[stateKey] : context;
352
- const { wrap, lock, syncRefHandle, manualUnlock } = typeof wrapOrOptions === 'boolean' ? { wrap: wrapOrOptions } : { ...wrapOrOptions };
390
+ function wrapPromise(promise, options) {
391
+ const { wrap, lock, syncRefHandle } = { ...options };
353
392
  let lockSwitchHook = undefined;
354
393
  let lockRefHandle = undefined;
355
- let lockKey = [];
356
394
  let needLock = false;
357
- let ignoreLock = false;
358
- const has = (val, key) => !!val && hasOwnProperty.call(val, key);
359
- const isObj = (obj) => objType(obj) === 'Object';
360
- const getValue = (obj, path) => {
361
- let result = false;
362
- if (obj && isObj(obj) && Array.isArray(path) && path.length) {
363
- let curObj = obj;
364
- for (let i = 0; i < path.length; i++) {
365
- const key = path[i];
366
- if (typeof curObj !== 'object' || !has(curObj, key)) {
367
- break;
368
- }
369
- curObj = curObj[key];
370
- i === path.length - 1 &&
371
- (result = (typeof curObj === 'boolean') ? curObj : false);
372
- }
373
- }
374
- return result;
375
- };
376
- const setValue = (obj, path, value) => {
377
- // if vue2 and path[0] not defined, do nothing
378
- if (contextType === 'vue' && context.$set && !has(obj, path[0]))
379
- return;
380
- const { $set = (o, key, val) => { o[key] = val; } } = context;
381
- const isStateRect = contextType === 'react';
382
- const originObj = isStateRect ? { ...obj } : obj;
383
- let curObj = originObj;
384
- let canSet = false;
385
- for (let i = 0; i < path.length; i++) {
386
- const key = path[i];
387
- const keyExist = has(curObj, key);
388
- if (i === path.length - 1) {
389
- const isBool = typeof curObj[key] === 'boolean';
390
- canSet = !keyExist || isBool;
391
- canSet && $set(curObj, key, value);
392
- }
393
- else {
394
- !keyExist && $set(curObj, key, {});
395
- if (!isObj(curObj[key]))
396
- break;
397
- isStateRect && (curObj[key] = { ...curObj[key] });
398
- curObj = curObj[key];
399
- }
400
- }
401
- // trigger setState when run in react class component
402
- isStateRect && canSet && context.setState({ [path[0]]: originObj[path[0]] });
403
- };
395
+ let isLocking = false;
404
396
  const stateLock = (bool) => {
405
- if (lockKey.length) {
406
- // if not reactive instance, save lock key as string, no need to structure nested object
407
- isReactiveIns ? setValue(contextState, lockKey, bool) : (lockCtx[lock] = bool);
408
- return;
409
- }
410
- if (lockRefHandle)
397
+ if (lockRefHandle) {
411
398
  lockRefHandle[0][lockRefHandle[1]] = bool;
412
- if (lockSwitchHook)
399
+ }
400
+ if (lockSwitchHook) {
413
401
  lockSwitchHook(bool);
402
+ }
414
403
  };
415
404
  const checkLock = () => {
416
- // use refHandle if contextState not update sync
417
- if (lockRefHandle)
418
- return lockRefHandle[0][lockRefHandle[1]];
419
- if (!isReactiveIns && typeof lock === 'string')
420
- return contextState[lock];
421
- return getValue(contextState, lockKey);
405
+ // use refHandle if state not update sync
406
+ return lockRefHandle ? lockRefHandle[0][lockRefHandle[1]] : false;
422
407
  };
423
408
  if (lock) {
424
- const isRefHandle = (val) => Array.isArray(val) && val.length === 2;
425
- if (typeof lock === 'string') {
426
- lockKey = lock.split('.');
427
- }
428
- else if (isRefHandle(lock)) {
409
+ const isRefHandle = (val) => isArr(val) && val.length === 2;
410
+ if (isRefHandle(lock)) {
429
411
  lockRefHandle = lock;
430
412
  }
431
- else if (typeof lock === 'function') {
413
+ else if (isFn(lock)) {
432
414
  lockSwitchHook = lock;
433
415
  if (isRefHandle(syncRefHandle)) {
434
416
  lockRefHandle = syncRefHandle;
435
417
  }
436
418
  }
437
- needLock = lockKey.length > 0 || !!lockRefHandle || !!lockSwitchHook;
438
- needLock && (ignoreLock = checkLock());
419
+ needLock = !!(lockSwitchHook || lockRefHandle);
420
+ needLock && (isLocking = checkLock());
439
421
  }
440
422
  let corePromsie;
441
423
  // if promise is a function, here need to call it in promise.then to use locking check to prevent next call
442
- if (typeof promise === 'function') {
443
- corePromsie = ignoreLock ? emptyPromise() : wrap ? awaitWrapper(promise()) : promise();
424
+ if (isFn(promise)) {
425
+ const truePromise = isLocking ? Promise.resolve(undefined) : promise();
426
+ corePromsie = wrap ? awaitWrapper(truePromise) : truePromise;
444
427
  }
445
428
  else {
446
429
  corePromsie = wrap ? awaitWrapper(promise) : promise;
447
430
  }
448
- const unlock = () => stateLock(false);
449
- Object.defineProperties(corePromsie, {
450
- '__lockValue': { get: checkLock },
451
- _checkLockKey: { value: (key) => lockCtx[key] },
452
- unlock: { value: unlock }
453
- });
454
- if (needLock && !ignoreLock) {
431
+ if (corePromsie instanceof Promise && needLock && !isLocking) {
455
432
  stateLock(true);
456
- !manualUnlock && corePromsie.finally(unlock);
433
+ corePromsie.finally(() => stateLock(false));
457
434
  }
458
435
  return corePromsie;
459
436
  }
460
- const wp = Object.defineProperty(wrapPromise, '_checkLockKey', { value: (key) => lockCtx[key] });
461
- const wpVuePlugin = {
462
- install(appOrVue, key = '$wp') {
463
- if (appOrVue.config && 'globalProperties' in appOrVue.config) {
464
- appOrVue.config.globalProperties[key] = wrapPromise;
465
- }
466
- else {
467
- appOrVue.prototype[key] = wrapPromise;
468
- }
469
- }
470
- };
437
+ /** short for method `wrapPromise` */
438
+ const wp = wrapPromise;
471
439
 
472
440
  function safeJsonParse(json = '', faileValue) {
473
441
  try {
@@ -489,17 +457,23 @@ const isNullable = (value) => value === '' || value === undefined || value === n
489
457
  */
490
458
  const filterNullable = (obj, deep) => {
491
459
  const result = {};
492
- Object.keys(obj).forEach(key => {
493
- const value = obj[key];
494
- if (value !== '' && value !== undefined && value !== null) {
495
- result[key] = deep && Object.prototype.toString.call(value) === '[object Object]' ? filterNullable(value) : value;
460
+ objForEch(obj, (key, value) => {
461
+ if (!isNullable(value)) {
462
+ if (!deep) {
463
+ result[key] = value;
464
+ }
465
+ else if (isArr(value)) {
466
+ result[key] = value.map((item) => isObj(item) ? filterNullable(item) : item);
467
+ }
468
+ else {
469
+ result[key] = isObj(value) ? filterNullable(value) : value;
470
+ }
496
471
  }
497
472
  });
498
473
  return result;
499
474
  };
500
- const { toString } = Object.prototype;
501
475
  /**
502
- * 将对象中属性值为null的转换为undefined
476
+ * 将对象中属性值为null的转换为undefined,会返回一个浅拷贝的新对象
503
477
  * @param data 对象数据
504
478
  * @returns
505
479
  */
@@ -507,13 +481,15 @@ const switchNullToUndefined = (data) => {
507
481
  if (data === null) {
508
482
  return undefined;
509
483
  }
510
- if (Array.isArray(data)) {
484
+ if (isArr(data)) {
511
485
  return data.map(switchNullToUndefined);
512
486
  }
513
- else if (toString.call(data) === '[object Object]') {
514
- Object.keys(data).forEach((key) => {
515
- data[key] = switchNullToUndefined(data[key]);
487
+ else if (isObj(data)) {
488
+ const result = {};
489
+ objForEch(data, (key, value) => {
490
+ result[key] = switchNullToUndefined(value);
516
491
  });
492
+ return result;
517
493
  }
518
494
  return data;
519
495
  };
@@ -527,7 +503,7 @@ const formParamsSwitch = (formData, maps, options) => {
527
503
  const dateKeys = Object.keys(maps);
528
504
  const dateData = {};
529
505
  const restData = {};
530
- Object.keys(formData).forEach(key => {
506
+ objForEch(formData, (key) => {
531
507
  if (dateKeys.includes(key)) {
532
508
  dateData[key] = formData[key];
533
509
  }
@@ -540,7 +516,10 @@ const formParamsSwitch = (formData, maps, options) => {
540
516
  if (accessKeys.length === 0) {
541
517
  return formData;
542
518
  }
543
- const { filterNullable: filterNullableValue, dateFormat } = { filterNullable: true, ...options };
519
+ const { filterNullable: filterNullableValue, dateFormat } = {
520
+ filterNullable: true,
521
+ ...options
522
+ };
544
523
  const handleData = accessKeys.reduce((acc, key) => {
545
524
  const values = dateData[key];
546
525
  const mapValue = maps[key];
@@ -549,7 +528,7 @@ const formParamsSwitch = (formData, maps, options) => {
549
528
  }
550
529
  // 数组合并操作/取最后一位操作
551
530
  if (mapValue === 'join' || mapValue === 'pop') {
552
- if (Array.isArray(values) && values.length) {
531
+ if (isArr(values) && values.length) {
553
532
  acc[key] = mapValue === 'join' ? values.join(',') : values.slice(-1)[0];
554
533
  }
555
534
  }
@@ -560,8 +539,10 @@ const formParamsSwitch = (formData, maps, options) => {
560
539
  const [startKey, endKey, format] = mapValue;
561
540
  const [startValue, endValue] = values;
562
541
  Object.assign(acc, {
563
- [startKey]: dateFormat instanceof Function ? dateFormat(startValue, format) : startValue,
564
- [endKey]: dateFormat instanceof Function ? dateFormat(endValue, format) : endValue
542
+ [startKey]: isFn(dateFormat)
543
+ ? dateFormat(startValue, format)
544
+ : startValue,
545
+ [endKey]: isFn(dateFormat) ? dateFormat(endValue, format) : endValue
565
546
  });
566
547
  }
567
548
  return acc;
@@ -575,12 +556,318 @@ const formParamsSwitch = (formData, maps, options) => {
575
556
  /** 创建一个绑定了默认时间格式转换函数的formParamsSwitch函数 */
576
557
  const formParamsSwitchCreator = (dateFormat) => (formData, maps, options) => formParamsSwitch(formData, maps, { dateFormat, ...options });
577
558
 
559
+ const isStr = (val) => typeof val === 'string';
560
+ const NOMETHOD = Symbol('NOMETHOD');
561
+ /**
562
+ * 创建emitter形式的实例,可以通过实例封装事件对象,比如websocket,得到一个更便捷的方法,具体可参考page-communicate.js文件内容
563
+ * @param options 配置项
564
+ * @returns
565
+ */
566
+ function eventTargetEmitter(options) {
567
+ const watchers = new Map([[NOMETHOD, new Set()]]);
568
+ const { name: currentName, customHanlderCreator } = options || {};
569
+ const customHanlder = isFn(customHanlderCreator)
570
+ ? customHanlderCreator(watchers)
571
+ : null;
572
+ const splitRegExp = /\|-[a-z]+-\|/;
573
+ const listenerSafeRun = (listener, ...args) => {
574
+ try {
575
+ listener(...args);
576
+ }
577
+ catch (e) {
578
+ console.error(e);
579
+ }
580
+ };
581
+ const defaultHanlder = (payload) => {
582
+ const { method, data, originEmitterName: from, targetEmitterName: to } = payload || [];
583
+ if (method && typeof method === 'string') {
584
+ const matchListeners = [];
585
+ watchers.forEach((value, key) => {
586
+ if (typeof key === 'string' && key.startsWith(method)) {
587
+ const [, eFrom] = key.split(splitRegExp);
588
+ if (!eFrom || !from || eFrom === from) {
589
+ matchListeners.push(...value);
590
+ }
591
+ }
592
+ });
593
+ if (matchListeners.length &&
594
+ (!currentName || !to || currentName === to)) {
595
+ matchListeners.forEach((listener) => listenerSafeRun(listener, data));
596
+ }
597
+ }
598
+ const noMethodListeners = watchers.get(NOMETHOD);
599
+ if (noMethodListeners) {
600
+ noMethodListeners.forEach((listener) => listenerSafeRun(listener, data, payload));
601
+ }
602
+ };
603
+ const rootEventListener = isFn(customHanlder) ? customHanlder : defaultHanlder;
604
+ const getFullMethodName = (method, options) => {
605
+ const { limitFrom = '', namespace = '' } = options || {};
606
+ return (limitFrom || namespace) && typeof method === 'string'
607
+ ? `${method}|-from-|${limitFrom}|-ns-|${namespace}`
608
+ : method;
609
+ };
610
+ const on = (method, listener, options) => {
611
+ if (typeof method === 'symbol' && method !== NOMETHOD) {
612
+ return;
613
+ }
614
+ const trueMethod = getFullMethodName(method, options);
615
+ if (!watchers.has(trueMethod)) {
616
+ watchers.set(trueMethod, new Set());
617
+ }
618
+ const listeners = watchers.get(trueMethod);
619
+ listeners?.add(listener);
620
+ };
621
+ const off = (method, callback, options) => {
622
+ if (typeof method === 'symbol' && method !== NOMETHOD) {
623
+ return;
624
+ }
625
+ const { namespace } = options || {};
626
+ if (namespace && !method) {
627
+ watchers.forEach((_value, key) => {
628
+ if (typeof key === 'string' && key.endsWith(namespace)) {
629
+ watchers.delete(key);
630
+ }
631
+ });
632
+ return;
633
+ }
634
+ const trueMethod = getFullMethodName(method, options);
635
+ if (!callback) {
636
+ watchers.delete(trueMethod);
637
+ return;
638
+ }
639
+ watchers.get(trueMethod)?.delete(callback);
640
+ };
641
+ const removeAllListeners = () => {
642
+ watchers.clear();
643
+ };
644
+ const createPayload = (methodOrPayload, data, target) => {
645
+ return isStr(methodOrPayload)
646
+ ? {
647
+ method: methodOrPayload,
648
+ data,
649
+ ...(target && isStr(target) ? { targetEmitterName: target } : {}),
650
+ ...(currentName && isStr(currentName)
651
+ ? { originEmitterName: currentName }
652
+ : {})
653
+ }
654
+ : methodOrPayload;
655
+ };
656
+ const emit = (...args) => {
657
+ const payload = createPayload(...args);
658
+ rootEventListener(payload);
659
+ };
660
+ /** 获取当前所有监听方法的方法名,默认仅返回函数名,设置all为true可以返回具体来源限制和命名空间字段 */
661
+ const getMethodNames = (all) => {
662
+ if (!all) {
663
+ const result = [];
664
+ watchers.forEach((_v, key) => isStr(key) && result.push(key.split(splitRegExp)));
665
+ return result;
666
+ }
667
+ const result = [];
668
+ watchers.forEach((_v, key) => isStr(key) && result.push(key));
669
+ return result;
670
+ };
671
+ const getListeners = (method, options) => {
672
+ if (typeof method === 'symbol') {
673
+ return method === NOMETHOD ? Array.from(watchers.get(NOMETHOD) || []) : [];
674
+ }
675
+ const trueMethod = getFullMethodName(method, options);
676
+ const listeners = watchers.get(trueMethod);
677
+ return listeners ? Array.from(listeners) : [];
678
+ };
679
+ return {
680
+ name: currentName,
681
+ rootEventListener,
682
+ on,
683
+ off,
684
+ emit,
685
+ createPayload,
686
+ removeAllListeners,
687
+ getMethodNames,
688
+ getListeners
689
+ };
690
+ }
691
+
692
+ /**
693
+ * 创建同源页面之间通信的封装实例,默认使用BroadcastChannel实现,在不支持的浏览器环境中会使用localstorage实现
694
+ * @param options 配置对象
695
+ * @returns
696
+ */
697
+ function pageCommunicate(options) {
698
+ const { messageHanlder, currentPage } = options || {};
699
+ const { emit, on, off, createPayload, removeAllListeners } = eventTargetEmitter({
700
+ name: currentPage,
701
+ customHanlderCreator: messageHanlder
702
+ });
703
+ const onMessage = (event) => emit(event.data);
704
+ let bc;
705
+ const ls = window.localStorage;
706
+ const channelName = 'PAGE_COMMUNICATE_CHANNEL';
707
+ if (typeof BroadcastChannel !== undefined) {
708
+ bc = new BroadcastChannel(channelName);
709
+ bc.addEventListener('message', onMessage);
710
+ }
711
+ else {
712
+ const onStorageMessage = () => {
713
+ const payload = safeJsonParse(ls.getItem(channelName) || '');
714
+ if (payload) {
715
+ emit(payload);
716
+ }
717
+ };
718
+ window.addEventListener('storage', onStorageMessage);
719
+ }
720
+ const send = (...args) => {
721
+ const payload = createPayload(...args);
722
+ if (bc) {
723
+ bc.postMessage(payload);
724
+ }
725
+ else {
726
+ const payloadWitchTs = JSON.stringify({ ...payload, ts: +new Date() });
727
+ ls.setItem(channelName, payloadWitchTs);
728
+ }
729
+ };
730
+ const destory = () => {
731
+ removeAllListeners();
732
+ if (bc) {
733
+ bc.close();
734
+ }
735
+ else {
736
+ ls.removeItem(channelName);
737
+ }
738
+ };
739
+ return { on, off, send, destory };
740
+ }
741
+
742
+ /**
743
+ * 创建一个计时器
744
+ * @returns
745
+ */
746
+ const createRAFTimer = (options) => {
747
+ const { autoStopWhenNoTask, autoStartWhenAddTask } = { ...options };
748
+ // 计时器句柄
749
+ let ticker = 0;
750
+ // 是否暂停状态
751
+ let paused = true;
752
+ // 计时器实际运行时间,不包括暂停区间
753
+ let timeStamp = 0;
754
+ // 上一次时序记录的时间戳
755
+ let lastTimeStamp = 0;
756
+ let tasks = [];
757
+ let taskNeedClear = false;
758
+ const timerHandler = (time) => {
759
+ const delta = time - (lastTimeStamp || time);
760
+ lastTimeStamp = time;
761
+ timeStamp += delta;
762
+ if (taskNeedClear) {
763
+ tasks = tasks.filter((item) => !item.needClear);
764
+ taskNeedClear = false;
765
+ }
766
+ // will auto stop when autoStopWhenNoTask is true and no task
767
+ if (autoStopWhenNoTask && !tasks.length) {
768
+ paused = true;
769
+ return;
770
+ }
771
+ tasks.forEach((item) => {
772
+ const { callback, maxTime, runTime, elapsed, interval, needClear } = item;
773
+ if (needClear) {
774
+ return;
775
+ }
776
+ if (maxTime && runTime >= maxTime) {
777
+ item.needClear = true;
778
+ taskNeedClear = true;
779
+ return;
780
+ }
781
+ if (elapsed >= interval) {
782
+ try {
783
+ callback(timeStamp);
784
+ }
785
+ catch (e) { }
786
+ item.elapsed = 0;
787
+ item.runTime += 1;
788
+ }
789
+ else {
790
+ item.elapsed += delta;
791
+ }
792
+ });
793
+ ticker = window.requestAnimationFrame(timerHandler);
794
+ };
795
+ /** start timer(开始计时器) */
796
+ const start = () => {
797
+ ticker = window.requestAnimationFrame(timerHandler);
798
+ paused = false;
799
+ };
800
+ /** stop timer(停止计时器) */
801
+ const stop = () => {
802
+ window.cancelAnimationFrame(ticker);
803
+ paused = true;
804
+ };
805
+ /** start/stop toggle (开启和停止切换) */
806
+ const pauseToggle = () => {
807
+ paused ? start() : stop();
808
+ };
809
+ const isPaused = () => paused;
810
+ /**
811
+ * add new task (添加定时任务,注意:无引用关系函数无法被remove,如需提前移除,需要确保函数可被寻到)
812
+ * @param callback task callback (任务回调函数)
813
+ * @param interval callback trigger interval, unit: ms (回调触发间隔,单位:ms)
814
+ * @param maxTime max time callback trigger (回调函数的最大触发次数)
815
+ */
816
+ const addTask = (callback, interval, maxTime) => {
817
+ if (!callback) {
818
+ return;
819
+ }
820
+ if (autoStartWhenAddTask && paused) {
821
+ start();
822
+ }
823
+ tasks.push({ callback, elapsed: 0, interval, maxTime, runTime: 0 });
824
+ };
825
+ /**
826
+ * remove task (移除定时任务)
827
+ * @param callback task callback (任务回调函数)
828
+ */
829
+ const removeTask = (callback) => {
830
+ tasks = tasks.filter((item) => item.callback !== callback);
831
+ };
832
+ return { start, stop, pauseToggle, addTask, removeTask, isPaused };
833
+ };
834
+
835
+ /**
836
+ * 将秒数转换为时间段对象
837
+ * @param number 秒数
838
+ * @param maxUnit 最大的单位,默认是小时
839
+ * @returns DurationDetail
840
+ */
841
+ const secondsToDuration = (number, maxUnit = 'h') => {
842
+ const secNum = Number.isInteger(number) ? number : Math.round(number);
843
+ const result = { s: secNum % 60 };
844
+ switch (maxUnit) {
845
+ case 'm':
846
+ result.m = Math.floor(secNum / 60);
847
+ break;
848
+ case 'h':
849
+ result.m = Math.floor((secNum % 3600) / 60);
850
+ result.h = Math.floor(secNum / 3600);
851
+ break;
852
+ case 'd':
853
+ result.m = Math.floor((secNum % 3600) / 60);
854
+ result.h = Math.floor((secNum % (3600 * 24)) / 3600);
855
+ result.d = Math.floor(secNum / 3600 / 24);
856
+ break;
857
+ }
858
+ return result;
859
+ };
860
+
578
861
  exports.ChinaIdCardValid = ChinaIdCardValid;
862
+ exports.NOMETHOD = NOMETHOD;
579
863
  exports.array2tree = array2tree;
580
864
  exports.awaitWrapper = awaitWrapper;
581
- exports.byteParse = byteParse;
865
+ exports.b64UriDecode = b64UriDecode;
866
+ exports.b64UriEncode = b64UriEncode;
582
867
  exports.byteStringify = byteStringify;
583
868
  exports.checkoutBy = checkoutBy;
869
+ exports.createRAFTimer = createRAFTimer;
870
+ exports.eventTargetEmitter = eventTargetEmitter;
584
871
  exports.filterNullable = filterNullable;
585
872
  exports.formParamsSwitch = formParamsSwitch;
586
873
  exports.formParamsSwitchCreator = formParamsSwitchCreator;
@@ -588,10 +875,10 @@ exports.formulaValidate = formulaValidate;
588
875
  exports.isNullable = isNullable;
589
876
  exports.mapToObject = mapToObject;
590
877
  exports.maskData = maskData;
591
- exports.objType = objType;
878
+ exports.pageCommunicate = pageCommunicate;
592
879
  exports.pickRenameKeys = pickRenameKeys;
593
880
  exports.safeJsonParse = safeJsonParse;
881
+ exports.secondsToDuration = secondsToDuration;
594
882
  exports.switchNullToUndefined = switchNullToUndefined;
595
883
  exports.tree2array = tree2array;
596
884
  exports.wp = wp;
597
- exports.wpVuePlugin = wpVuePlugin;