@wxhccc/es-util 1.7.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1,22 +1,25 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.7.0
2
+ * @wxhccc/es-util v2.0.0
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,7 +264,11 @@ 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)
@@ -237,14 +292,14 @@ function byteStringify(byteNum, options) {
237
292
  const getValue = (value) => Number.isInteger(value) ? value : value.toFixed(precision);
238
293
  let resUnit = '';
239
294
  let resValue = 0;
240
- if (!Array.isArray(unitMap)) {
295
+ if (!isArr(unitMap)) {
241
296
  const maxValue = Math.pow(base, unitMap.expMax);
242
297
  resUnit = unitMap.units[standard];
243
298
  const value = byteNumber / maxValue;
244
299
  resValue = getValue(value * negative);
245
300
  }
246
301
  else {
247
- unitMap.some(item => {
302
+ unitMap.some((item) => {
248
303
  const maxValue = Math.pow(base, item.expMax);
249
304
  const value = byteNumber / maxValue;
250
305
  if (value > base)
@@ -255,9 +310,6 @@ function byteStringify(byteNum, options) {
255
310
  });
256
311
  }
257
312
  return detail ? { value: resValue, unit: resUnit } : `${resValue} ${resUnit}`;
258
- }
259
- // translate string to byte num
260
- function byteParse(byteStr, options = {}) {
261
313
  }
262
314
 
263
315
  const modeIndexs = {
@@ -274,7 +326,9 @@ function maskData(data, options) {
274
326
  if (typeof data !== 'string' || !data) {
275
327
  return '';
276
328
  }
277
- const modeOpts = options && options.mode && modeIndexs[options.mode] ? modeIndexs[options.mode] : {};
329
+ const modeOpts = options && options.mode && modeIndexs[options.mode]
330
+ ? modeIndexs[options.mode]
331
+ : {};
278
332
  const { maskWith, startCharIndex: start = 0, endCharIndex: end, startFrom, endUntil } = { maskWith: '*', ...modeOpts, ...options };
279
333
  let handleData = data;
280
334
  let beforeChars = '';
@@ -293,7 +347,10 @@ function maskData(data, options) {
293
347
  const chars = handleData.split('');
294
348
  const newChars = [beforeChars];
295
349
  const charLen = chars.length;
296
- const indexs = [start >= 0 ? start : charLen + start, end !== undefined ? (end >= 0 ? end : charLen + end) : charLen - 1];
350
+ const indexs = [
351
+ start >= 0 ? start : charLen + start,
352
+ end !== undefined ? (end >= 0 ? end : charLen + end) : charLen - 1
353
+ ];
297
354
  let [startIdx, endIdx] = indexs;
298
355
  endIdx = endIdx > 0 && endIdx < charLen ? endIdx : charLen - 1;
299
356
  startIdx = startIdx >= 0 && startIdx <= endIdx ? startIdx : 0;
@@ -304,11 +361,15 @@ function maskData(data, options) {
304
361
  return newChars.join('');
305
362
  }
306
363
 
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
- };
364
+ /**
365
+ * 将字符串编码为base64, 采用encodeURIComponent+window.btoa,主要为了解决atob/btoa处理特殊字符会报错的问题,性能不如buffer方案,适用于简单场景
366
+ * @param str 待转换的字符串
367
+ * @returns
368
+ */
369
+ const b64UriEncode = (str) => window.btoa(encodeURIComponent(str));
370
+ /** b64UriEncode对应的解码函数 */
371
+ const b64UriDecode = (str) => decodeURIComponent(window.atob(str));
372
+
312
373
  /**
313
374
  * wrap promise and handle reject or err by return an array like [error, undefined]
314
375
  * @param promise promise
@@ -323,158 +384,55 @@ async function awaitWrapper(promise) {
323
384
  return [err, undefined];
324
385
  }
325
386
  }
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 };
387
+ function wrapPromise(promise, options) {
388
+ const { wrap, lock, syncRefHandle } = { ...options };
360
389
  let lockSwitchHook = undefined;
361
390
  let lockRefHandle = undefined;
362
- let lockKey = [];
363
391
  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
- };
392
+ let isLocking = false;
411
393
  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)
394
+ if (lockRefHandle) {
418
395
  lockRefHandle[0][lockRefHandle[1]] = bool;
419
- if (lockSwitchHook)
396
+ }
397
+ if (lockSwitchHook) {
420
398
  lockSwitchHook(bool);
399
+ }
421
400
  };
422
401
  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);
402
+ // use refHandle if state not update sync
403
+ return lockRefHandle ? lockRefHandle[0][lockRefHandle[1]] : false;
429
404
  };
430
405
  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)) {
406
+ const isRefHandle = (val) => isArr(val) && val.length === 2;
407
+ if (isRefHandle(lock)) {
436
408
  lockRefHandle = lock;
437
409
  }
438
- else if (typeof lock === 'function') {
410
+ else if (isFn(lock)) {
439
411
  lockSwitchHook = lock;
440
412
  if (isRefHandle(syncRefHandle)) {
441
413
  lockRefHandle = syncRefHandle;
442
414
  }
443
415
  }
444
- needLock = lockKey.length > 0 || !!lockRefHandle || !!lockSwitchHook;
445
- needLock && (ignoreLock = checkLock());
416
+ needLock = !!(lockSwitchHook || lockRefHandle);
417
+ needLock && (isLocking = checkLock());
446
418
  }
447
419
  let corePromsie;
448
420
  // 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();
421
+ if (isFn(promise)) {
422
+ const truePromise = isLocking ? Promise.resolve(undefined) : promise();
423
+ corePromsie = wrap ? awaitWrapper(truePromise) : truePromise;
451
424
  }
452
425
  else {
453
426
  corePromsie = wrap ? awaitWrapper(promise) : promise;
454
427
  }
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) {
428
+ if (corePromsie instanceof Promise && needLock && !isLocking) {
462
429
  stateLock(true);
463
- !manualUnlock && corePromsie.finally(unlock);
430
+ corePromsie.finally(() => stateLock(false));
464
431
  }
465
432
  return corePromsie;
466
433
  }
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
- };
434
+ /** short for method `wrapPromise` */
435
+ const wp = wrapPromise;
478
436
 
479
437
  function safeJsonParse(json = '', faileValue) {
480
438
  try {
@@ -496,17 +454,23 @@ const isNullable = (value) => value === '' || value === undefined || value === n
496
454
  */
497
455
  const filterNullable = (obj, deep) => {
498
456
  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;
457
+ objForEch(obj, (key, value) => {
458
+ if (!isNullable(value)) {
459
+ if (!deep) {
460
+ result[key] = value;
461
+ }
462
+ else if (isArr(value)) {
463
+ result[key] = value.map((item) => isObj(item) ? filterNullable(item) : item);
464
+ }
465
+ else {
466
+ result[key] = isObj(value) ? filterNullable(value) : value;
467
+ }
503
468
  }
504
469
  });
505
470
  return result;
506
471
  };
507
- const { toString } = Object.prototype;
508
472
  /**
509
- * 将对象中属性值为null的转换为undefined
473
+ * 将对象中属性值为null的转换为undefined,会返回一个浅拷贝的新对象
510
474
  * @param data 对象数据
511
475
  * @returns
512
476
  */
@@ -514,13 +478,15 @@ const switchNullToUndefined = (data) => {
514
478
  if (data === null) {
515
479
  return undefined;
516
480
  }
517
- if (Array.isArray(data)) {
481
+ if (isArr(data)) {
518
482
  return data.map(switchNullToUndefined);
519
483
  }
520
- else if (toString.call(data) === '[object Object]') {
521
- Object.keys(data).forEach((key) => {
522
- data[key] = switchNullToUndefined(data[key]);
484
+ else if (isObj(data)) {
485
+ const result = {};
486
+ objForEch(data, (key, value) => {
487
+ result[key] = switchNullToUndefined(value);
523
488
  });
489
+ return result;
524
490
  }
525
491
  return data;
526
492
  };
@@ -534,7 +500,7 @@ const formParamsSwitch = (formData, maps, options) => {
534
500
  const dateKeys = Object.keys(maps);
535
501
  const dateData = {};
536
502
  const restData = {};
537
- Object.keys(formData).forEach(key => {
503
+ objForEch(formData, (key) => {
538
504
  if (dateKeys.includes(key)) {
539
505
  dateData[key] = formData[key];
540
506
  }
@@ -547,7 +513,10 @@ const formParamsSwitch = (formData, maps, options) => {
547
513
  if (accessKeys.length === 0) {
548
514
  return formData;
549
515
  }
550
- const { filterNullable: filterNullableValue, dateFormat } = { filterNullable: true, ...options };
516
+ const { filterNullable: filterNullableValue, dateFormat } = {
517
+ filterNullable: true,
518
+ ...options
519
+ };
551
520
  const handleData = accessKeys.reduce((acc, key) => {
552
521
  const values = dateData[key];
553
522
  const mapValue = maps[key];
@@ -556,7 +525,7 @@ const formParamsSwitch = (formData, maps, options) => {
556
525
  }
557
526
  // 数组合并操作/取最后一位操作
558
527
  if (mapValue === 'join' || mapValue === 'pop') {
559
- if (Array.isArray(values) && values.length) {
528
+ if (isArr(values) && values.length) {
560
529
  acc[key] = mapValue === 'join' ? values.join(',') : values.slice(-1)[0];
561
530
  }
562
531
  }
@@ -567,8 +536,10 @@ const formParamsSwitch = (formData, maps, options) => {
567
536
  const [startKey, endKey, format] = mapValue;
568
537
  const [startValue, endValue] = values;
569
538
  Object.assign(acc, {
570
- [startKey]: dateFormat instanceof Function ? dateFormat(startValue, format) : startValue,
571
- [endKey]: dateFormat instanceof Function ? dateFormat(endValue, format) : endValue
539
+ [startKey]: isFn(dateFormat)
540
+ ? dateFormat(startValue, format)
541
+ : startValue,
542
+ [endKey]: isFn(dateFormat) ? dateFormat(endValue, format) : endValue
572
543
  });
573
544
  }
574
545
  return acc;
@@ -592,7 +563,9 @@ const NOMETHOD = Symbol('NOMETHOD');
592
563
  function eventTargetEmitter(options) {
593
564
  const watchers = new Map([[NOMETHOD, new Set()]]);
594
565
  const { name: currentName, customHanlderCreator } = options || {};
595
- const customHanlder = customHanlderCreator instanceof Function ? customHanlderCreator(watchers) : null;
566
+ const customHanlder = isFn(customHanlderCreator)
567
+ ? customHanlderCreator(watchers)
568
+ : null;
596
569
  const splitRegExp = /\|-[a-z]+-\|/;
597
570
  const listenerSafeRun = (listener, ...args) => {
598
571
  try {
@@ -608,25 +581,28 @@ function eventTargetEmitter(options) {
608
581
  const matchListeners = [];
609
582
  watchers.forEach((value, key) => {
610
583
  if (typeof key === 'string' && key.startsWith(method)) {
611
- const [, eFrom,] = key.split(splitRegExp);
584
+ const [, eFrom] = key.split(splitRegExp);
612
585
  if (!eFrom || !from || eFrom === from) {
613
586
  matchListeners.push(...value);
614
587
  }
615
588
  }
616
589
  });
617
- if (matchListeners.length && (!currentName || !to || currentName === to)) {
618
- matchListeners.forEach(listener => listenerSafeRun(listener, data));
590
+ if (matchListeners.length &&
591
+ (!currentName || !to || currentName === to)) {
592
+ matchListeners.forEach((listener) => listenerSafeRun(listener, data));
619
593
  }
620
594
  }
621
595
  const noMethodListeners = watchers.get(NOMETHOD);
622
596
  if (noMethodListeners) {
623
- noMethodListeners.forEach(listener => listenerSafeRun(listener, data, payload));
597
+ noMethodListeners.forEach((listener) => listenerSafeRun(listener, data, payload));
624
598
  }
625
599
  };
626
- const rootEventListener = customHanlder instanceof Function ? customHanlder : defaultHanlder;
600
+ const rootEventListener = isFn(customHanlder) ? customHanlder : defaultHanlder;
627
601
  const getFullMethodName = (method, options) => {
628
602
  const { limitFrom = '', namespace = '' } = options || {};
629
- return (limitFrom || namespace) && typeof method === 'string' ? `${method}|-from-|${limitFrom}|-ns-|${namespace}` : method;
603
+ return (limitFrom || namespace) && typeof method === 'string'
604
+ ? `${method}|-from-|${limitFrom}|-ns-|${namespace}`
605
+ : method;
630
606
  };
631
607
  const on = (method, listener, options) => {
632
608
  if (typeof method === 'symbol' && method !== NOMETHOD) {
@@ -643,7 +619,7 @@ function eventTargetEmitter(options) {
643
619
  if (typeof method === 'symbol' && method !== NOMETHOD) {
644
620
  return;
645
621
  }
646
- const { limitFrom, namespace } = options || {};
622
+ const { namespace } = options || {};
647
623
  if (namespace && !method) {
648
624
  watchers.forEach((_value, key) => {
649
625
  if (typeof key === 'string' && key.endsWith(namespace)) {
@@ -663,12 +639,16 @@ function eventTargetEmitter(options) {
663
639
  watchers.clear();
664
640
  };
665
641
  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;
642
+ return isStr(methodOrPayload)
643
+ ? {
644
+ method: methodOrPayload,
645
+ data,
646
+ ...(target && isStr(target) ? { targetEmitterName: target } : {}),
647
+ ...(currentName && isStr(currentName)
648
+ ? { originEmitterName: currentName }
649
+ : {})
650
+ }
651
+ : methodOrPayload;
672
652
  };
673
653
  const emit = (...args) => {
674
654
  const payload = createPayload(...args);
@@ -693,7 +673,17 @@ function eventTargetEmitter(options) {
693
673
  const listeners = watchers.get(trueMethod);
694
674
  return listeners ? Array.from(listeners) : [];
695
675
  };
696
- return { name: currentName, rootEventListener, on, off, emit, createPayload, removeAllListeners, getMethodNames, getListeners };
676
+ return {
677
+ name: currentName,
678
+ rootEventListener,
679
+ on,
680
+ off,
681
+ emit,
682
+ createPayload,
683
+ removeAllListeners,
684
+ getMethodNames,
685
+ getListeners
686
+ };
697
687
  }
698
688
 
699
689
  /**
@@ -703,7 +693,10 @@ function eventTargetEmitter(options) {
703
693
  */
704
694
  function pageCommunicate(options) {
705
695
  const { messageHanlder, currentPage } = options || {};
706
- const { emit, on, off, createPayload, removeAllListeners } = eventTargetEmitter({ name: currentPage, customHanlderCreator: messageHanlder });
696
+ const { emit, on, off, createPayload, removeAllListeners } = eventTargetEmitter({
697
+ name: currentPage,
698
+ customHanlderCreator: messageHanlder
699
+ });
707
700
  const onMessage = (event) => emit(event.data);
708
701
  let bc;
709
702
  const ls = window.localStorage;
@@ -743,4 +736,123 @@ function pageCommunicate(options) {
743
736
  return { on, off, send, destory };
744
737
  }
745
738
 
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 };
739
+ /**
740
+ * 创建一个计时器
741
+ * @returns
742
+ */
743
+ const createRAFTimer = (options) => {
744
+ const { autoStopWhenNoTask, autoStartWhenAddTask } = { ...options };
745
+ // 计时器句柄
746
+ let ticker = 0;
747
+ // 是否暂停状态
748
+ let paused = true;
749
+ // 计时器实际运行时间,不包括暂停区间
750
+ let timeStamp = 0;
751
+ // 上一次时序记录的时间戳
752
+ let lastTimeStamp = 0;
753
+ let tasks = [];
754
+ let taskNeedClear = false;
755
+ const timerHandler = (time) => {
756
+ const delta = time - (lastTimeStamp || time);
757
+ lastTimeStamp = time;
758
+ timeStamp += delta;
759
+ if (taskNeedClear) {
760
+ tasks = tasks.filter((item) => !item.needClear);
761
+ taskNeedClear = false;
762
+ }
763
+ // will auto stop when autoStopWhenNoTask is true and no task
764
+ if (autoStopWhenNoTask && !tasks.length) {
765
+ paused = true;
766
+ return;
767
+ }
768
+ tasks.forEach((item) => {
769
+ const { callback, maxTime, runTime, elapsed, interval, needClear } = item;
770
+ if (needClear) {
771
+ return;
772
+ }
773
+ if (maxTime && runTime >= maxTime) {
774
+ item.needClear = true;
775
+ taskNeedClear = true;
776
+ return;
777
+ }
778
+ if (elapsed >= interval) {
779
+ try {
780
+ callback(timeStamp);
781
+ }
782
+ catch (e) { }
783
+ item.elapsed = 0;
784
+ item.runTime += 1;
785
+ }
786
+ else {
787
+ item.elapsed += delta;
788
+ }
789
+ });
790
+ ticker = window.requestAnimationFrame(timerHandler);
791
+ };
792
+ /** start timer(开始计时器) */
793
+ const start = () => {
794
+ ticker = window.requestAnimationFrame(timerHandler);
795
+ paused = false;
796
+ };
797
+ /** stop timer(停止计时器) */
798
+ const stop = () => {
799
+ window.cancelAnimationFrame(ticker);
800
+ paused = true;
801
+ };
802
+ /** start/stop toggle (开启和停止切换) */
803
+ const pauseToggle = () => {
804
+ paused ? start() : stop();
805
+ };
806
+ const isPaused = () => paused;
807
+ /**
808
+ * add new task (添加定时任务,注意:无引用关系函数无法被remove,如需提前移除,需要确保函数可被寻到)
809
+ * @param callback task callback (任务回调函数)
810
+ * @param interval callback trigger interval, unit: ms (回调触发间隔,单位:ms)
811
+ * @param maxTime max time callback trigger (回调函数的最大触发次数)
812
+ */
813
+ const addTask = (callback, interval, maxTime) => {
814
+ if (!callback) {
815
+ return;
816
+ }
817
+ if (autoStartWhenAddTask && paused) {
818
+ start();
819
+ }
820
+ tasks.push({ callback, elapsed: 0, interval, maxTime, runTime: 0 });
821
+ };
822
+ /**
823
+ * remove task (移除定时任务)
824
+ * @param callback task callback (任务回调函数)
825
+ */
826
+ const removeTask = (callback) => {
827
+ tasks = tasks.filter((item) => item.callback !== callback);
828
+ };
829
+ return { start, stop, pauseToggle, addTask, removeTask, isPaused };
830
+ };
831
+
832
+ /**
833
+ * 将秒数转换为时间段对象
834
+ * @param number 秒数
835
+ * @param maxUnit 最大的单位,默认是小时
836
+ * @returns DurationDetail
837
+ */
838
+ const secondsToDuration = (number, maxUnit = 'h') => {
839
+ const secNum = Number.isInteger(number) ? number : Math.round(number);
840
+ const result = { s: secNum % 60 };
841
+ switch (maxUnit) {
842
+ case 'm':
843
+ result.m = Math.floor(secNum / 60);
844
+ break;
845
+ case 'h':
846
+ result.m = Math.floor((secNum % 3600) / 60);
847
+ result.h = Math.floor(secNum / 3600);
848
+ break;
849
+ case 'd':
850
+ result.m = Math.floor((secNum % 3600) / 60);
851
+ result.h = Math.floor((secNum % (3600 * 24)) / 3600);
852
+ result.d = Math.floor(secNum / 3600 / 24);
853
+ break;
854
+ }
855
+ return result;
856
+ };
857
+
858
+ 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 };