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