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