@wxhccc/es-util 1.7.0 → 2.0.2

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/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.7.0
2
+ * @wxhccc/es-util v2.0.2
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -7,20 +7,23 @@
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
28
  const { primaryKey: id, parentKey: pid, childrenKey: children, createRoot, parentRefKey } = {
26
29
  primaryKey: 'id',
@@ -30,15 +33,19 @@ function array2tree(array, options = {}) {
30
33
  parentRefKey: false,
31
34
  ...options
32
35
  };
33
- const pRefKey = parentRefKey && (typeof parentRefKey === 'string' ? parentRefKey : '_parent');
34
- let nodeMap = {};
35
- let treeNodes = [];
36
- Array.isArray(array) && array.forEach(item => {
37
- !hasOwnProperty$1.call(nodeMap, item[id]) && (nodeMap[item[id]] = Object.assign({}, item, createNode(children)));
38
- hasOwnProperty$1.call(nodeMap, item[pid]) && nodeMap[item[pid]][children].push(Object.assign(nodeMap[item[id]], pRefKey ? { [pRefKey]: nodeMap[item[pid]] } : {}));
39
- !item[pid] && treeNodes.push(nodeMap[item[id]]);
40
- });
41
- if (createRoot instanceof Function) {
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)) {
42
49
  return createRoot(treeNodes);
43
50
  }
44
51
  else if (createRoot) {
@@ -47,22 +54,12 @@ function array2tree(array, options = {}) {
47
54
  return treeNodes;
48
55
  }
49
56
  function nodeChildFilter(node, childrenKey) {
50
- let newNode = {};
51
- for (let i in node) {
57
+ const newNode = {};
58
+ for (const i in node) {
52
59
  i !== childrenKey && (newNode[i] = node[i]);
53
60
  }
54
61
  return newNode;
55
62
  }
56
- /**
57
- * translate tree to array
58
- * @param {Array/Object} tree the node tree need to be translate
59
- * @param {Object} options the options
60
- * @param {string} primaryKey the primary key of tree node
61
- * @param {string} parentKey the parent's key of tree node
62
- * @param {string} childrenKey the child's key of tree node
63
- * @param {boolean} hasParentKey whether create parent id in node
64
- * @param {boolean} returnObject whether return object or array
65
- */
66
63
  function tree2array(tree, options = {}) {
67
64
  const { primaryKey: id, parentKey: pid, childrenKey: children, hasParentKey, returnObject } = Object.assign({
68
65
  hasParentKey: true,
@@ -71,20 +68,22 @@ function tree2array(tree, options = {}) {
71
68
  childrenKey: 'children',
72
69
  returnObject: false
73
70
  }, options);
74
- let nodes = returnObject ? {} : [];
75
- if (!Array.isArray(tree) && typeof tree !== 'object')
71
+ const nodes = returnObject ? {} : [];
72
+ if (!isArr(tree) && typeof tree !== 'object')
76
73
  return nodes;
77
74
  function getNode(node, parentId, root = false) {
78
- let baseNode = hasParentKey ? {} : { [pid]: parentId };
75
+ const baseNode = hasParentKey ? {} : { [pid]: parentId };
79
76
  if (!root) {
80
77
  const newNode = Object.assign(baseNode, nodeChildFilter(node, children));
81
- returnObject ? (nodes[node[id]] = newNode) : nodes.push(newNode);
78
+ returnObject
79
+ ? (nodes[node[id]] = newNode)
80
+ : nodes.push(newNode);
82
81
  }
83
- if (Array.isArray(node[children]) && node[children].length) {
82
+ if (isArr(node[children]) && node[children].length) {
84
83
  node[children].forEach((childNode) => getNode(childNode, node[id]));
85
84
  }
86
85
  }
87
- const rootTree = Array.isArray(tree) ? createNode(children, tree) : tree;
86
+ const rootTree = isArr(tree) ? createNode(children, tree) : tree;
88
87
  getNode(rootTree, null, true);
89
88
  return nodes;
90
89
  }
@@ -94,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{
94
93
  /* 身份证合法性验证 */
95
94
  function ChinaIdCardValid(idNo) {
96
95
  const idNumber = idNo.toString().toUpperCase();
97
- 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
+ ];
98
133
  const lastCodeCheck = () => {
99
134
  if (idNumber.length === 18) {
100
135
  const chars = idNumber.split('');
@@ -116,7 +151,9 @@ function ChinaIdCardValid(idNo) {
116
151
  }
117
152
  return true;
118
153
  };
119
- 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());
120
157
  }
121
158
  // 公式验证函数
122
159
  function formulaValidate(string, variables) {
@@ -128,7 +165,8 @@ function formulaValidate(string, variables) {
128
165
  const bns = /[^+\-*/]\(/; // 错误情况,(前面不是运算符
129
166
  const blns = /\)[^+\-*/]/; // 错误情况,)后面不是运算符
130
167
  const bmatch = () => {
131
- let stack = [];
168
+ // 错误情况,括号不配对
169
+ const stack = [];
132
170
  for (let i = 0, item; i < string.length; i++) {
133
171
  item = string.charAt(i);
134
172
  if (item === '(') {
@@ -149,41 +187,54 @@ function formulaValidate(string, variables) {
149
187
  const varInList = (vars) => {
150
188
  const tmpStr = string.replace(/[()+\-*/]{1,}/g, '`');
151
189
  const array = tmpStr.split('`');
152
- 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));
153
191
  };
154
- 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)));
155
200
  }
156
201
 
157
202
  function mapToObject(objectArray, keyProp = 'key', valueProp = 'value') {
158
203
  const result = {};
159
- Array.isArray(objectArray) && keyProp && valueProp
160
- && [keyProp, valueProp].every(val => ['string', 'function'].includes(typeof val))
161
- && objectArray.forEach((item, index) => {
204
+ isArr(objectArray) &&
205
+ keyProp &&
206
+ valueProp &&
207
+ [keyProp, valueProp].every((val) => ['string', 'function'].includes(typeof val)) &&
208
+ objectArray.forEach((item, index) => {
162
209
  const key = typeof keyProp === 'string' ? item[keyProp] : keyProp(item, index);
163
210
  const value = typeof valueProp === 'string' ? item[valueProp] : valueProp(item, index);
164
211
  ['string', 'number'].includes(typeof key) && (result[key] = value);
165
212
  });
166
213
  return result;
167
214
  }
168
- const isObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]';
169
215
  /**
170
216
  * checkout values form object as an array
171
- *
217
+ * 从对象中挑选指定的值并以数组形式返回,必要时可使用自定义属性覆盖选中对象
172
218
  * @param {Object} object
173
219
  * @param {string[] | Object} keys
174
220
  * @param {string} valueProp
175
221
  */
176
222
  function checkoutBy(object, keys, mergeFn) {
177
- if (!isObject(object)) {
223
+ if (!isObj(object)) {
178
224
  return [];
179
225
  }
180
- if (Array.isArray(keys)) {
181
- return keys.map(item => object[item]);
226
+ if (isArr(keys)) {
227
+ return keys.map((key) => object[key]);
182
228
  }
183
- else if (keys && isObject(keys)) {
184
- return Object.keys(keys).map(item => (isObject(object[item]) && isObject(keys[item]))
185
- ? (mergeFn ? mergeFn({}, (object)[item], (keys)[item]) : Object.assign({}, object[item], keys[item]))
186
- : (keys[item] || object[item]));
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
+ });
187
238
  }
188
239
  return Object.values(object);
189
240
  }
@@ -194,12 +245,12 @@ function checkoutBy(object, keys, mergeFn) {
194
245
  * @param {Object} keysMap
195
246
  */
196
247
  function pickRenameKeys(object, keysMap) {
197
- if (!object || !isObject(object) || !keysMap || !isObject(keysMap)) {
248
+ if (!object || !isObj(object) || !keysMap || !isObj(keysMap)) {
198
249
  return;
199
250
  }
200
- let result = {};
201
- for (let i in object) {
202
- (i in keysMap) && (result[keysMap[i]] = object[i]);
251
+ const result = {};
252
+ for (const i in object) {
253
+ i in keysMap && (result[keysMap[i]] = object[i]);
203
254
  }
204
255
  return result;
205
256
  }
@@ -217,13 +268,16 @@ const configCreater = (standard, unit) => {
217
268
  Z: { expMax: 7, units: { metric: 'ZB', iec: 'ZiB', jedec: 'ZB' } },
218
269
  Y: { expMax: 8, units: { metric: 'YB', iec: 'YiB', jedec: 'YB' } }
219
270
  };
220
- const standBase = { metric: 1000, iec: 1024, jedec: 1024 };
271
+ const standBase = {
272
+ metric: 1000,
273
+ iec: 1024,
274
+ jedec: 1024
275
+ };
221
276
  return {
222
277
  base: standBase[standard] || standBase['jedec'],
223
278
  unitMap: unitMap[unit] || Object.values(unitMap)
224
279
  };
225
280
  };
226
- // translate byte num to string
227
281
  function byteStringify(byteNum, options) {
228
282
  const opts = Object.assign({
229
283
  standard: 'jedec',
@@ -241,14 +295,14 @@ function byteStringify(byteNum, options) {
241
295
  const getValue = (value) => Number.isInteger(value) ? value : value.toFixed(precision);
242
296
  let resUnit = '';
243
297
  let resValue = 0;
244
- if (!Array.isArray(unitMap)) {
298
+ if (!isArr(unitMap)) {
245
299
  const maxValue = Math.pow(base, unitMap.expMax);
246
300
  resUnit = unitMap.units[standard];
247
301
  const value = byteNumber / maxValue;
248
302
  resValue = getValue(value * negative);
249
303
  }
250
304
  else {
251
- unitMap.some(item => {
305
+ unitMap.some((item) => {
252
306
  const maxValue = Math.pow(base, item.expMax);
253
307
  const value = byteNumber / maxValue;
254
308
  if (value > base)
@@ -259,9 +313,6 @@ function byteStringify(byteNum, options) {
259
313
  });
260
314
  }
261
315
  return detail ? { value: resValue, unit: resUnit } : `${resValue} ${resUnit}`;
262
- }
263
- // translate string to byte num
264
- function byteParse(byteStr, options = {}) {
265
316
  }
266
317
 
267
318
  const modeIndexs = {
@@ -278,7 +329,9 @@ function maskData(data, options) {
278
329
  if (typeof data !== 'string' || !data) {
279
330
  return '';
280
331
  }
281
- 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
+ : {};
282
335
  const { maskWith, startCharIndex: start = 0, endCharIndex: end, startFrom, endUntil } = { maskWith: '*', ...modeOpts, ...options };
283
336
  let handleData = data;
284
337
  let beforeChars = '';
@@ -297,7 +350,10 @@ function maskData(data, options) {
297
350
  const chars = handleData.split('');
298
351
  const newChars = [beforeChars];
299
352
  const charLen = chars.length;
300
- 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
+ ];
301
357
  let [startIdx, endIdx] = indexs;
302
358
  endIdx = endIdx > 0 && endIdx < charLen ? endIdx : charLen - 1;
303
359
  startIdx = startIdx >= 0 && startIdx <= endIdx ? startIdx : 0;
@@ -308,11 +364,15 @@ function maskData(data, options) {
308
364
  return newChars.join('');
309
365
  }
310
366
 
311
- const { hasOwnProperty, toString: toString$1 } = Object.prototype;
312
- const objType = (val) => {
313
- const typeKeys = toString$1.call(val).match(/^\[object (.*)\]$/);
314
- return typeKeys ? typeKeys[1] : '';
315
- };
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
+
316
376
  /**
317
377
  * wrap promise and handle reject or err by return an array like [error, undefined]
318
378
  * @param promise promise
@@ -327,158 +387,55 @@ async function awaitWrapper(promise) {
327
387
  return [err, undefined];
328
388
  }
329
389
  }
330
- function checkContext(context) {
331
- if (!context)
332
- return 'unknown';
333
- if (context._isVue || (context.$ && context.$.vnode)) {
334
- return 'vue';
335
- }
336
- else if ('setState' in context) {
337
- return 'react';
338
- }
339
- return 'unknown';
340
- }
341
- const emptyPromise = () => {
342
- const ep = Promise.resolve(undefined);
343
- return Object.assign(ep, {
344
- then(...args) {
345
- const [onfulfilled] = args;
346
- // if then has be called by Promise.all, let ite pass
347
- if (args.length === 2 && typeof onfulfilled === 'function') {
348
- return onfulfilled(undefined);
349
- }
350
- return ep;
351
- },
352
- catch: (onrejected) => ep,
353
- finally: () => ep
354
- });
355
- };
356
- const lockCtx = {};
357
- function wrapPromise(promise, wrapOrOptions) {
358
- const contextType = checkContext(this);
359
- const isReactiveIns = contextType !== 'unknown';
360
- const context = isReactiveIns ? this : lockCtx;
361
- const stateKey = contextType === 'react' ? 'state' : '';
362
- const contextState = stateKey ? context[stateKey] : context;
363
- const { wrap, lock, syncRefHandle, manualUnlock } = typeof wrapOrOptions === 'boolean' ? { wrap: wrapOrOptions } : { ...wrapOrOptions };
390
+ function wrapPromise(promise, options) {
391
+ const { wrap, lock, syncRefHandle } = { ...options };
364
392
  let lockSwitchHook = undefined;
365
393
  let lockRefHandle = undefined;
366
- let lockKey = [];
367
394
  let needLock = false;
368
- let ignoreLock = false;
369
- const has = (val, key) => !!val && hasOwnProperty.call(val, key);
370
- const isObj = (obj) => objType(obj) === 'Object';
371
- const getValue = (obj, path) => {
372
- let result = false;
373
- if (obj && isObj(obj) && Array.isArray(path) && path.length) {
374
- let curObj = obj;
375
- for (let i = 0; i < path.length; i++) {
376
- const key = path[i];
377
- if (typeof curObj !== 'object' || !has(curObj, key)) {
378
- break;
379
- }
380
- curObj = curObj[key];
381
- i === path.length - 1 &&
382
- (result = (typeof curObj === 'boolean') ? curObj : false);
383
- }
384
- }
385
- return result;
386
- };
387
- const setValue = (obj, path, value) => {
388
- // if vue2 and path[0] not defined, do nothing
389
- if (contextType === 'vue' && context.$set && !has(obj, path[0]))
390
- return;
391
- const { $set = (o, key, val) => { o[key] = val; } } = context;
392
- const isStateRect = contextType === 'react';
393
- const originObj = isStateRect ? { ...obj } : obj;
394
- let curObj = originObj;
395
- let canSet = false;
396
- for (let i = 0; i < path.length; i++) {
397
- const key = path[i];
398
- const keyExist = has(curObj, key);
399
- if (i === path.length - 1) {
400
- const isBool = typeof curObj[key] === 'boolean';
401
- canSet = !keyExist || isBool;
402
- canSet && $set(curObj, key, value);
403
- }
404
- else {
405
- !keyExist && $set(curObj, key, {});
406
- if (!isObj(curObj[key]))
407
- break;
408
- isStateRect && (curObj[key] = { ...curObj[key] });
409
- curObj = curObj[key];
410
- }
411
- }
412
- // trigger setState when run in react class component
413
- isStateRect && canSet && context.setState({ [path[0]]: originObj[path[0]] });
414
- };
395
+ let isLocking = false;
415
396
  const stateLock = (bool) => {
416
- if (lockKey.length) {
417
- // if not reactive instance, save lock key as string, no need to structure nested object
418
- isReactiveIns ? setValue(contextState, lockKey, bool) : (lockCtx[lock] = bool);
419
- return;
420
- }
421
- if (lockRefHandle)
397
+ if (lockRefHandle) {
422
398
  lockRefHandle[0][lockRefHandle[1]] = bool;
423
- if (lockSwitchHook)
399
+ }
400
+ if (lockSwitchHook) {
424
401
  lockSwitchHook(bool);
402
+ }
425
403
  };
426
404
  const checkLock = () => {
427
- // use refHandle if contextState not update sync
428
- if (lockRefHandle)
429
- return lockRefHandle[0][lockRefHandle[1]];
430
- if (!isReactiveIns && typeof lock === 'string')
431
- return contextState[lock];
432
- return getValue(contextState, lockKey);
405
+ // use refHandle if state not update sync
406
+ return lockRefHandle ? lockRefHandle[0][lockRefHandle[1]] : false;
433
407
  };
434
408
  if (lock) {
435
- const isRefHandle = (val) => Array.isArray(val) && val.length === 2;
436
- if (typeof lock === 'string') {
437
- lockKey = lock.split('.');
438
- }
439
- else if (isRefHandle(lock)) {
409
+ const isRefHandle = (val) => isArr(val) && val.length === 2;
410
+ if (isRefHandle(lock)) {
440
411
  lockRefHandle = lock;
441
412
  }
442
- else if (typeof lock === 'function') {
413
+ else if (isFn(lock)) {
443
414
  lockSwitchHook = lock;
444
415
  if (isRefHandle(syncRefHandle)) {
445
416
  lockRefHandle = syncRefHandle;
446
417
  }
447
418
  }
448
- needLock = lockKey.length > 0 || !!lockRefHandle || !!lockSwitchHook;
449
- needLock && (ignoreLock = checkLock());
419
+ needLock = !!(lockSwitchHook || lockRefHandle);
420
+ needLock && (isLocking = checkLock());
450
421
  }
451
422
  let corePromsie;
452
423
  // if promise is a function, here need to call it in promise.then to use locking check to prevent next call
453
- if (typeof promise === 'function') {
454
- 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;
455
427
  }
456
428
  else {
457
429
  corePromsie = wrap ? awaitWrapper(promise) : promise;
458
430
  }
459
- const unlock = () => stateLock(false);
460
- Object.defineProperties(corePromsie, {
461
- '__lockValue': { get: checkLock },
462
- _checkLockKey: { value: (key) => lockCtx[key] },
463
- unlock: { value: unlock }
464
- });
465
- if (needLock && !ignoreLock) {
431
+ if (corePromsie instanceof Promise && needLock && !isLocking) {
466
432
  stateLock(true);
467
- !manualUnlock && corePromsie.finally(unlock);
433
+ corePromsie.finally(() => stateLock(false));
468
434
  }
469
435
  return corePromsie;
470
436
  }
471
- const wp = Object.defineProperty(wrapPromise, '_checkLockKey', { value: (key) => lockCtx[key] });
472
- const wpVuePlugin = {
473
- install(appOrVue, key = '$wp') {
474
- if (appOrVue.config && 'globalProperties' in appOrVue.config) {
475
- appOrVue.config.globalProperties[key] = wrapPromise;
476
- }
477
- else {
478
- appOrVue.prototype[key] = wrapPromise;
479
- }
480
- }
481
- };
437
+ /** short for method `wrapPromise` */
438
+ const wp = wrapPromise;
482
439
 
483
440
  function safeJsonParse(json = '', faileValue) {
484
441
  try {
@@ -500,17 +457,23 @@ const isNullable = (value) => value === '' || value === undefined || value === n
500
457
  */
501
458
  const filterNullable = (obj, deep) => {
502
459
  const result = {};
503
- Object.keys(obj).forEach(key => {
504
- const value = obj[key];
505
- if (value !== '' && value !== undefined && value !== null) {
506
- 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
+ }
507
471
  }
508
472
  });
509
473
  return result;
510
474
  };
511
- const { toString } = Object.prototype;
512
475
  /**
513
- * 将对象中属性值为null的转换为undefined
476
+ * 将对象中属性值为null的转换为undefined,会返回一个浅拷贝的新对象
514
477
  * @param data 对象数据
515
478
  * @returns
516
479
  */
@@ -518,13 +481,15 @@ const switchNullToUndefined = (data) => {
518
481
  if (data === null) {
519
482
  return undefined;
520
483
  }
521
- if (Array.isArray(data)) {
484
+ if (isArr(data)) {
522
485
  return data.map(switchNullToUndefined);
523
486
  }
524
- else if (toString.call(data) === '[object Object]') {
525
- Object.keys(data).forEach((key) => {
526
- data[key] = switchNullToUndefined(data[key]);
487
+ else if (isObj(data)) {
488
+ const result = {};
489
+ objForEch(data, (key, value) => {
490
+ result[key] = switchNullToUndefined(value);
527
491
  });
492
+ return result;
528
493
  }
529
494
  return data;
530
495
  };
@@ -538,7 +503,7 @@ const formParamsSwitch = (formData, maps, options) => {
538
503
  const dateKeys = Object.keys(maps);
539
504
  const dateData = {};
540
505
  const restData = {};
541
- Object.keys(formData).forEach(key => {
506
+ objForEch(formData, (key) => {
542
507
  if (dateKeys.includes(key)) {
543
508
  dateData[key] = formData[key];
544
509
  }
@@ -551,7 +516,10 @@ const formParamsSwitch = (formData, maps, options) => {
551
516
  if (accessKeys.length === 0) {
552
517
  return formData;
553
518
  }
554
- const { filterNullable: filterNullableValue, dateFormat } = { filterNullable: true, ...options };
519
+ const { filterNullable: filterNullableValue, dateFormat } = {
520
+ filterNullable: true,
521
+ ...options
522
+ };
555
523
  const handleData = accessKeys.reduce((acc, key) => {
556
524
  const values = dateData[key];
557
525
  const mapValue = maps[key];
@@ -560,7 +528,7 @@ const formParamsSwitch = (formData, maps, options) => {
560
528
  }
561
529
  // 数组合并操作/取最后一位操作
562
530
  if (mapValue === 'join' || mapValue === 'pop') {
563
- if (Array.isArray(values) && values.length) {
531
+ if (isArr(values) && values.length) {
564
532
  acc[key] = mapValue === 'join' ? values.join(',') : values.slice(-1)[0];
565
533
  }
566
534
  }
@@ -571,8 +539,10 @@ const formParamsSwitch = (formData, maps, options) => {
571
539
  const [startKey, endKey, format] = mapValue;
572
540
  const [startValue, endValue] = values;
573
541
  Object.assign(acc, {
574
- [startKey]: dateFormat instanceof Function ? dateFormat(startValue, format) : startValue,
575
- [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
576
546
  });
577
547
  }
578
548
  return acc;
@@ -596,7 +566,9 @@ const NOMETHOD = Symbol('NOMETHOD');
596
566
  function eventTargetEmitter(options) {
597
567
  const watchers = new Map([[NOMETHOD, new Set()]]);
598
568
  const { name: currentName, customHanlderCreator } = options || {};
599
- const customHanlder = customHanlderCreator instanceof Function ? customHanlderCreator(watchers) : null;
569
+ const customHanlder = isFn(customHanlderCreator)
570
+ ? customHanlderCreator(watchers)
571
+ : null;
600
572
  const splitRegExp = /\|-[a-z]+-\|/;
601
573
  const listenerSafeRun = (listener, ...args) => {
602
574
  try {
@@ -612,25 +584,28 @@ function eventTargetEmitter(options) {
612
584
  const matchListeners = [];
613
585
  watchers.forEach((value, key) => {
614
586
  if (typeof key === 'string' && key.startsWith(method)) {
615
- const [, eFrom,] = key.split(splitRegExp);
587
+ const [, eFrom] = key.split(splitRegExp);
616
588
  if (!eFrom || !from || eFrom === from) {
617
589
  matchListeners.push(...value);
618
590
  }
619
591
  }
620
592
  });
621
- if (matchListeners.length && (!currentName || !to || currentName === to)) {
622
- matchListeners.forEach(listener => listenerSafeRun(listener, data));
593
+ if (matchListeners.length &&
594
+ (!currentName || !to || currentName === to)) {
595
+ matchListeners.forEach((listener) => listenerSafeRun(listener, data));
623
596
  }
624
597
  }
625
598
  const noMethodListeners = watchers.get(NOMETHOD);
626
599
  if (noMethodListeners) {
627
- noMethodListeners.forEach(listener => listenerSafeRun(listener, data, payload));
600
+ noMethodListeners.forEach((listener) => listenerSafeRun(listener, data, payload));
628
601
  }
629
602
  };
630
- const rootEventListener = customHanlder instanceof Function ? customHanlder : defaultHanlder;
603
+ const rootEventListener = isFn(customHanlder) ? customHanlder : defaultHanlder;
631
604
  const getFullMethodName = (method, options) => {
632
605
  const { limitFrom = '', namespace = '' } = options || {};
633
- return (limitFrom || namespace) && typeof method === 'string' ? `${method}|-from-|${limitFrom}|-ns-|${namespace}` : method;
606
+ return (limitFrom || namespace) && typeof method === 'string'
607
+ ? `${method}|-from-|${limitFrom}|-ns-|${namespace}`
608
+ : method;
634
609
  };
635
610
  const on = (method, listener, options) => {
636
611
  if (typeof method === 'symbol' && method !== NOMETHOD) {
@@ -647,7 +622,7 @@ function eventTargetEmitter(options) {
647
622
  if (typeof method === 'symbol' && method !== NOMETHOD) {
648
623
  return;
649
624
  }
650
- const { limitFrom, namespace } = options || {};
625
+ const { namespace } = options || {};
651
626
  if (namespace && !method) {
652
627
  watchers.forEach((_value, key) => {
653
628
  if (typeof key === 'string' && key.endsWith(namespace)) {
@@ -667,12 +642,16 @@ function eventTargetEmitter(options) {
667
642
  watchers.clear();
668
643
  };
669
644
  const createPayload = (methodOrPayload, data, target) => {
670
- return isStr(methodOrPayload) ? {
671
- method: methodOrPayload,
672
- data,
673
- ...(target && isStr(target) ? { targetEmitterName: target } : {}),
674
- ...(currentName && isStr(currentName) ? { originEmitterName: currentName } : {})
675
- } : methodOrPayload;
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;
676
655
  };
677
656
  const emit = (...args) => {
678
657
  const payload = createPayload(...args);
@@ -697,7 +676,17 @@ function eventTargetEmitter(options) {
697
676
  const listeners = watchers.get(trueMethod);
698
677
  return listeners ? Array.from(listeners) : [];
699
678
  };
700
- return { name: currentName, rootEventListener, on, off, emit, createPayload, removeAllListeners, getMethodNames, getListeners };
679
+ return {
680
+ name: currentName,
681
+ rootEventListener,
682
+ on,
683
+ off,
684
+ emit,
685
+ createPayload,
686
+ removeAllListeners,
687
+ getMethodNames,
688
+ getListeners
689
+ };
701
690
  }
702
691
 
703
692
  /**
@@ -707,12 +696,15 @@ function eventTargetEmitter(options) {
707
696
  */
708
697
  function pageCommunicate(options) {
709
698
  const { messageHanlder, currentPage } = options || {};
710
- const { emit, on, off, createPayload, removeAllListeners } = eventTargetEmitter({ name: currentPage, customHanlderCreator: messageHanlder });
699
+ const { emit, on, off, createPayload, removeAllListeners } = eventTargetEmitter({
700
+ name: currentPage,
701
+ customHanlderCreator: messageHanlder
702
+ });
711
703
  const onMessage = (event) => emit(event.data);
712
704
  let bc;
713
705
  const ls = window.localStorage;
714
706
  const channelName = 'PAGE_COMMUNICATE_CHANNEL';
715
- if (typeof BroadcastChannel !== undefined) {
707
+ if (typeof window.BroadcastChannel !== undefined) {
716
708
  bc = new BroadcastChannel(channelName);
717
709
  bc.addEventListener('message', onMessage);
718
710
  }
@@ -747,13 +739,134 @@ function pageCommunicate(options) {
747
739
  return { on, off, send, destory };
748
740
  }
749
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
+
750
861
  exports.ChinaIdCardValid = ChinaIdCardValid;
751
862
  exports.NOMETHOD = NOMETHOD;
752
863
  exports.array2tree = array2tree;
753
864
  exports.awaitWrapper = awaitWrapper;
754
- exports.byteParse = byteParse;
865
+ exports.b64UriDecode = b64UriDecode;
866
+ exports.b64UriEncode = b64UriEncode;
755
867
  exports.byteStringify = byteStringify;
756
868
  exports.checkoutBy = checkoutBy;
869
+ exports.createRAFTimer = createRAFTimer;
757
870
  exports.eventTargetEmitter = eventTargetEmitter;
758
871
  exports.filterNullable = filterNullable;
759
872
  exports.formParamsSwitch = formParamsSwitch;
@@ -762,11 +875,10 @@ exports.formulaValidate = formulaValidate;
762
875
  exports.isNullable = isNullable;
763
876
  exports.mapToObject = mapToObject;
764
877
  exports.maskData = maskData;
765
- exports.objType = objType;
766
878
  exports.pageCommunicate = pageCommunicate;
767
879
  exports.pickRenameKeys = pickRenameKeys;
768
880
  exports.safeJsonParse = safeJsonParse;
881
+ exports.secondsToDuration = secondsToDuration;
769
882
  exports.switchNullToUndefined = switchNullToUndefined;
770
883
  exports.tree2array = tree2array;
771
884
  exports.wp = wp;
772
- exports.wpVuePlugin = wpVuePlugin;