@wxhccc/es-util 1.5.2 → 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,39 +1,47 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.5.2
3
- * (c) 2021 wxhccc
2
+ * @wxhccc/es-util v2.0.0
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
- const { primaryKey: id, parentKey: pid, childrenKey: children, createRoot, parentRefKey } = Object.assign({
24
+ const { primaryKey: id, parentKey: pid, childrenKey: children, createRoot, parentRefKey } = {
22
25
  primaryKey: 'id',
23
26
  parentKey: 'pid',
24
27
  childrenKey: 'children',
25
28
  createRoot: false,
26
- parentRefKey: false
27
- }, options);
28
- const pRefKey = parentRefKey && (typeof parentRefKey === 'string' ? parentRefKey : '_parent');
29
- let nodeMap = {};
30
- let treeNodes = [];
31
- Array.isArray(array) && array.forEach(item => {
32
- !hasOwnProperty$1.call(nodeMap, item[id]) && (nodeMap[item[id]] = Object.assign({}, item, createNode(children)));
33
- hasOwnProperty$1.call(nodeMap, item[pid]) && nodeMap[item[pid]][children].push(Object.assign(nodeMap[item[id]], pRefKey ? { [pRefKey]: nodeMap[item[pid]] } : {}));
34
- !item[pid] && treeNodes.push(nodeMap[item[id]]);
35
- });
36
- if (typeof createRoot === 'function') {
29
+ parentRefKey: false,
30
+ ...options
31
+ };
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)) {
37
45
  return createRoot(treeNodes);
38
46
  }
39
47
  else if (createRoot) {
@@ -42,22 +50,12 @@ function array2tree(array, options = {}) {
42
50
  return treeNodes;
43
51
  }
44
52
  function nodeChildFilter(node, childrenKey) {
45
- let newNode = {};
46
- for (let i in node) {
53
+ const newNode = {};
54
+ for (const i in node) {
47
55
  i !== childrenKey && (newNode[i] = node[i]);
48
56
  }
49
57
  return newNode;
50
58
  }
51
- /**
52
- * translate tree to array
53
- * @param {Array/Object} tree the node tree need to be translate
54
- * @param {Object} options the options
55
- * @param {string} primaryKey the primary key of tree node
56
- * @param {string} parentKey the parent's key of tree node
57
- * @param {string} childrenKey the child's key of tree node
58
- * @param {boolean} hasParentKey whether create parent id in node
59
- * @param {boolean} returnObject whether return object or array
60
- */
61
59
  function tree2array(tree, options = {}) {
62
60
  const { primaryKey: id, parentKey: pid, childrenKey: children, hasParentKey, returnObject } = Object.assign({
63
61
  hasParentKey: true,
@@ -66,20 +64,22 @@ function tree2array(tree, options = {}) {
66
64
  childrenKey: 'children',
67
65
  returnObject: false
68
66
  }, options);
69
- let nodes = returnObject ? {} : [];
70
- if (!Array.isArray(tree) && typeof tree !== 'object')
67
+ const nodes = returnObject ? {} : [];
68
+ if (!isArr(tree) && typeof tree !== 'object')
71
69
  return nodes;
72
70
  function getNode(node, parentId, root = false) {
73
- let baseNode = hasParentKey ? {} : { [pid]: parentId };
71
+ const baseNode = hasParentKey ? {} : { [pid]: parentId };
74
72
  if (!root) {
75
73
  const newNode = Object.assign(baseNode, nodeChildFilter(node, children));
76
- returnObject ? (nodes[node[id]] = newNode) : nodes.push(newNode);
74
+ returnObject
75
+ ? (nodes[node[id]] = newNode)
76
+ : nodes.push(newNode);
77
77
  }
78
- if (Array.isArray(node[children]) && node[children].length) {
78
+ if (isArr(node[children]) && node[children].length) {
79
79
  node[children].forEach((childNode) => getNode(childNode, node[id]));
80
80
  }
81
81
  }
82
- const rootTree = Array.isArray(tree) ? createNode(children, tree) : tree;
82
+ const rootTree = isArr(tree) ? createNode(children, tree) : tree;
83
83
  getNode(rootTree, null, true);
84
84
  return nodes;
85
85
  }
@@ -89,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{
89
89
  /* 身份证合法性验证 */
90
90
  function ChinaIdCardValid(idNo) {
91
91
  const idNumber = idNo.toString().toUpperCase();
92
- 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
+ ];
93
129
  const lastCodeCheck = () => {
94
130
  if (idNumber.length === 18) {
95
131
  const chars = idNumber.split('');
@@ -111,7 +147,9 @@ function ChinaIdCardValid(idNo) {
111
147
  }
112
148
  return true;
113
149
  };
114
- 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());
115
153
  }
116
154
  // 公式验证函数
117
155
  function formulaValidate(string, variables) {
@@ -123,7 +161,8 @@ function formulaValidate(string, variables) {
123
161
  const bns = /[^+\-*/]\(/; // 错误情况,(前面不是运算符
124
162
  const blns = /\)[^+\-*/]/; // 错误情况,)后面不是运算符
125
163
  const bmatch = () => {
126
- let stack = [];
164
+ // 错误情况,括号不配对
165
+ const stack = [];
127
166
  for (let i = 0, item; i < string.length; i++) {
128
167
  item = string.charAt(i);
129
168
  if (item === '(') {
@@ -144,32 +183,54 @@ function formulaValidate(string, variables) {
144
183
  const varInList = (vars) => {
145
184
  const tmpStr = string.replace(/[()+\-*/]{1,}/g, '`');
146
185
  const array = tmpStr.split('`');
147
- 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));
148
187
  };
149
- 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)));
150
196
  }
151
197
 
152
198
  function mapToObject(objectArray, keyProp = 'key', valueProp = 'value') {
153
- let result = {};
154
- Array.isArray(objectArray) && keyProp && valueProp
155
- && [keyProp, valueProp].every(val => ['string', 'function'].includes(typeof val))
156
- && objectArray.forEach((item, index) => {
199
+ const result = {};
200
+ isArr(objectArray) &&
201
+ keyProp &&
202
+ valueProp &&
203
+ [keyProp, valueProp].every((val) => ['string', 'function'].includes(typeof val)) &&
204
+ objectArray.forEach((item, index) => {
157
205
  const key = typeof keyProp === 'string' ? item[keyProp] : keyProp(item, index);
158
206
  const value = typeof valueProp === 'string' ? item[valueProp] : valueProp(item, index);
159
207
  ['string', 'number'].includes(typeof key) && (result[key] = value);
160
208
  });
161
209
  return result;
162
210
  }
211
+ /**
212
+ * checkout values form object as an array
213
+ * 从对象中挑选指定的值并以数组形式返回,必要时可使用自定义属性覆盖选中对象
214
+ * @param {Object} object
215
+ * @param {string[] | Object} keys
216
+ * @param {string} valueProp
217
+ */
163
218
  function checkoutBy(object, keys, mergeFn) {
164
- if (!(object instanceof Object))
219
+ if (!isObj(object)) {
165
220
  return [];
166
- if (Array.isArray(keys)) {
167
- return keys.map(item => (object[item]));
168
221
  }
169
- else if (keys && keys instanceof Object) {
170
- return Object.keys(keys).map(item => (object[item] instanceof Object && keys[item] instanceof Object)
171
- ? (mergeFn ? mergeFn({}, object[item], keys[item]) : Object.assign({}, object[item], keys[item]))
172
- : (keys[item] || object[item]));
222
+ if (isArr(keys)) {
223
+ return keys.map((key) => object[key]);
224
+ }
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
+ });
173
234
  }
174
235
  return Object.values(object);
175
236
  }
@@ -180,11 +241,12 @@ function checkoutBy(object, keys, mergeFn) {
180
241
  * @param {Object} keysMap
181
242
  */
182
243
  function pickRenameKeys(object, keysMap) {
183
- if (!object || !(object instanceof Object) || !keysMap || !(keysMap instanceof Object))
244
+ if (!object || !isObj(object) || !keysMap || !isObj(keysMap)) {
184
245
  return;
185
- let result = {};
186
- for (let i in object) {
187
- (i in keysMap) && (result[keysMap[i]] = object[i]);
246
+ }
247
+ const result = {};
248
+ for (const i in object) {
249
+ i in keysMap && (result[keysMap[i]] = object[i]);
188
250
  }
189
251
  return result;
190
252
  }
@@ -202,7 +264,11 @@ const configCreater = (standard, unit) => {
202
264
  Z: { expMax: 7, units: { metric: 'ZB', iec: 'ZiB', jedec: 'ZB' } },
203
265
  Y: { expMax: 8, units: { metric: 'YB', iec: 'YiB', jedec: 'YB' } }
204
266
  };
205
- const standBase = { metric: 1000, iec: 1024, jedec: 1024 };
267
+ const standBase = {
268
+ metric: 1000,
269
+ iec: 1024,
270
+ jedec: 1024
271
+ };
206
272
  return {
207
273
  base: standBase[standard] || standBase['jedec'],
208
274
  unitMap: unitMap[unit] || Object.values(unitMap)
@@ -226,14 +292,14 @@ function byteStringify(byteNum, options) {
226
292
  const getValue = (value) => Number.isInteger(value) ? value : value.toFixed(precision);
227
293
  let resUnit = '';
228
294
  let resValue = 0;
229
- if (!Array.isArray(unitMap)) {
295
+ if (!isArr(unitMap)) {
230
296
  const maxValue = Math.pow(base, unitMap.expMax);
231
297
  resUnit = unitMap.units[standard];
232
298
  const value = byteNumber / maxValue;
233
299
  resValue = getValue(value * negative);
234
300
  }
235
301
  else {
236
- unitMap.some(item => {
302
+ unitMap.some((item) => {
237
303
  const maxValue = Math.pow(base, item.expMax);
238
304
  const value = byteNumber / maxValue;
239
305
  if (value > base)
@@ -244,16 +310,66 @@ function byteStringify(byteNum, options) {
244
310
  });
245
311
  }
246
312
  return detail ? { value: resValue, unit: resUnit } : `${resValue} ${resUnit}`;
247
- }
248
- // translate string to byte num
249
- function byteParse(byteStr, options = {}) {
250
313
  }
251
314
 
252
- const { hasOwnProperty, toString: toString$1 } = Object.prototype;
253
- const objType = (val) => {
254
- const typeKeys = toString$1.call(val).match(/^\[object (.*)\]$/);
255
- return typeKeys ? typeKeys[1] : '';
315
+ const modeIndexs = {
316
+ telphone: { startCharIndex: -8, endCharIndex: -5 },
317
+ idcard: { startCharIndex: -12, endCharIndex: -5 }
256
318
  };
319
+ /**
320
+ * 对给定的字符串进行脱敏处理
321
+ * @param data 需要处理的字符串
322
+ * @param options 配置参数对象
323
+ * @returns
324
+ */
325
+ function maskData(data, options) {
326
+ if (typeof data !== 'string' || !data) {
327
+ return '';
328
+ }
329
+ const modeOpts = options && options.mode && modeIndexs[options.mode]
330
+ ? modeIndexs[options.mode]
331
+ : {};
332
+ const { maskWith, startCharIndex: start = 0, endCharIndex: end, startFrom, endUntil } = { maskWith: '*', ...modeOpts, ...options };
333
+ let handleData = data;
334
+ let beforeChars = '';
335
+ let afterChars = '';
336
+ const startFromIndex = startFrom ? data.indexOf(startFrom) : -1;
337
+ if (startFromIndex > -1) {
338
+ const index = startFromIndex + startFrom.length;
339
+ handleData = handleData.slice(index);
340
+ beforeChars = data.slice(0, index);
341
+ }
342
+ const endUtilIndex = endUntil ? data.lastIndexOf(endUntil) : -1;
343
+ if (endUtilIndex > -1) {
344
+ handleData = handleData.slice(0, endUtilIndex);
345
+ afterChars = data.slice(endUtilIndex);
346
+ }
347
+ const chars = handleData.split('');
348
+ const newChars = [beforeChars];
349
+ const charLen = chars.length;
350
+ const indexs = [
351
+ start >= 0 ? start : charLen + start,
352
+ end !== undefined ? (end >= 0 ? end : charLen + end) : charLen - 1
353
+ ];
354
+ let [startIdx, endIdx] = indexs;
355
+ endIdx = endIdx > 0 && endIdx < charLen ? endIdx : charLen - 1;
356
+ startIdx = startIdx >= 0 && startIdx <= endIdx ? startIdx : 0;
357
+ chars.forEach((char, idx) => {
358
+ newChars.push(idx >= startIdx && idx <= endIdx ? maskWith : char);
359
+ });
360
+ newChars.push(afterChars);
361
+ return newChars.join('');
362
+ }
363
+
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
+
257
373
  /**
258
374
  * wrap promise and handle reject or err by return an array like [error, undefined]
259
375
  * @param promise promise
@@ -268,158 +384,55 @@ async function awaitWrapper(promise) {
268
384
  return [err, undefined];
269
385
  }
270
386
  }
271
- function checkContext(context) {
272
- if (!context)
273
- return 'unknown';
274
- if (context._isVue || (context.$ && context.$.vnode)) {
275
- return 'vue';
276
- }
277
- else if ('setState' in context) {
278
- return 'react';
279
- }
280
- return 'unknown';
281
- }
282
- const emptyPromise = () => {
283
- const ep = Promise.resolve(undefined);
284
- return Object.assign(ep, {
285
- then(...args) {
286
- const [onfulfilled] = args;
287
- // if then has be called by Promise.all, let ite pass
288
- if (args.length === 2 && typeof onfulfilled === 'function') {
289
- return onfulfilled(undefined);
290
- }
291
- return ep;
292
- },
293
- catch: (onrejected) => ep,
294
- finally: () => ep
295
- });
296
- };
297
- const lockCtx = {};
298
- function wrapPromise(promise, wrapOrOptions) {
299
- const contextType = checkContext(this);
300
- const isReactiveIns = contextType !== 'unknown';
301
- const context = isReactiveIns ? this : lockCtx;
302
- const stateKey = contextType === 'react' ? 'state' : '';
303
- const contextState = stateKey ? context[stateKey] : context;
304
- const { wrap, lock, syncRefHandle, manualUnlock } = typeof wrapOrOptions === 'boolean' ? { wrap: wrapOrOptions } : { ...wrapOrOptions };
387
+ function wrapPromise(promise, options) {
388
+ const { wrap, lock, syncRefHandle } = { ...options };
305
389
  let lockSwitchHook = undefined;
306
390
  let lockRefHandle = undefined;
307
- let lockKey = [];
308
391
  let needLock = false;
309
- let ignoreLock = false;
310
- const has = (val, key) => !!val && hasOwnProperty.call(val, key);
311
- const isObj = (obj) => objType(obj) === 'Object';
312
- const getValue = (obj, path) => {
313
- let result = false;
314
- if (obj && isObj(obj) && Array.isArray(path) && path.length) {
315
- let curObj = obj;
316
- for (let i = 0; i < path.length; i++) {
317
- const key = path[i];
318
- if (typeof curObj !== 'object' || !has(curObj, key)) {
319
- break;
320
- }
321
- curObj = curObj[key];
322
- i === path.length - 1 &&
323
- (result = (typeof curObj === 'boolean') ? curObj : false);
324
- }
325
- }
326
- return result;
327
- };
328
- const setValue = (obj, path, value) => {
329
- // if vue2 and path[0] not defined, do nothing
330
- if (contextType === 'vue' && context.$set && !has(obj, path[0]))
331
- return;
332
- const { $set = (o, key, val) => { o[key] = val; } } = context;
333
- const isStateRect = contextType === 'react';
334
- const originObj = isStateRect ? { ...obj } : obj;
335
- let curObj = originObj;
336
- let canSet = false;
337
- for (let i = 0; i < path.length; i++) {
338
- const key = path[i];
339
- const keyExist = has(curObj, key);
340
- if (i === path.length - 1) {
341
- const isBool = typeof curObj[key] === 'boolean';
342
- canSet = !keyExist || isBool;
343
- canSet && $set(curObj, key, value);
344
- }
345
- else {
346
- !keyExist && $set(curObj, key, {});
347
- if (!isObj(curObj[key]))
348
- break;
349
- isStateRect && (curObj[key] = { ...curObj[key] });
350
- curObj = curObj[key];
351
- }
352
- }
353
- // trigger setState when run in react class component
354
- isStateRect && canSet && context.setState({ [path[0]]: originObj[path[0]] });
355
- };
392
+ let isLocking = false;
356
393
  const stateLock = (bool) => {
357
- if (lockKey.length) {
358
- // if not reactive instance, save lock key as string, no need to structure nested object
359
- isReactiveIns ? setValue(contextState, lockKey, bool) : (lockCtx[lock] = bool);
360
- return;
361
- }
362
- if (lockRefHandle)
394
+ if (lockRefHandle) {
363
395
  lockRefHandle[0][lockRefHandle[1]] = bool;
364
- if (lockSwitchHook)
396
+ }
397
+ if (lockSwitchHook) {
365
398
  lockSwitchHook(bool);
399
+ }
366
400
  };
367
401
  const checkLock = () => {
368
- // use refHandle if contextState not update sync
369
- if (lockRefHandle)
370
- return lockRefHandle[0][lockRefHandle[1]];
371
- if (!isReactiveIns && typeof lock === 'string')
372
- return contextState[lock];
373
- return getValue(contextState, lockKey);
402
+ // use refHandle if state not update sync
403
+ return lockRefHandle ? lockRefHandle[0][lockRefHandle[1]] : false;
374
404
  };
375
405
  if (lock) {
376
- const isRefHandle = (val) => Array.isArray(val) && val.length === 2;
377
- if (typeof lock === 'string') {
378
- lockKey = lock.split('.');
379
- }
380
- else if (isRefHandle(lock)) {
406
+ const isRefHandle = (val) => isArr(val) && val.length === 2;
407
+ if (isRefHandle(lock)) {
381
408
  lockRefHandle = lock;
382
409
  }
383
- else if (typeof lock === 'function') {
410
+ else if (isFn(lock)) {
384
411
  lockSwitchHook = lock;
385
412
  if (isRefHandle(syncRefHandle)) {
386
413
  lockRefHandle = syncRefHandle;
387
414
  }
388
415
  }
389
- needLock = lockKey.length > 0 || !!lockRefHandle || !!lockSwitchHook;
390
- needLock && (ignoreLock = checkLock());
416
+ needLock = !!(lockSwitchHook || lockRefHandle);
417
+ needLock && (isLocking = checkLock());
391
418
  }
392
419
  let corePromsie;
393
420
  // if promise is a function, here need to call it in promise.then to use locking check to prevent next call
394
- if (typeof promise === 'function') {
395
- 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;
396
424
  }
397
425
  else {
398
426
  corePromsie = wrap ? awaitWrapper(promise) : promise;
399
427
  }
400
- const unlock = () => stateLock(false);
401
- Object.defineProperties(corePromsie, {
402
- '__lockValue': { get: checkLock },
403
- _checkLockKey: { value: (key) => lockCtx[key] },
404
- unlock: { value: unlock }
405
- });
406
- if (needLock && !ignoreLock) {
428
+ if (corePromsie instanceof Promise && needLock && !isLocking) {
407
429
  stateLock(true);
408
- !manualUnlock && corePromsie.finally(unlock);
430
+ corePromsie.finally(() => stateLock(false));
409
431
  }
410
432
  return corePromsie;
411
433
  }
412
- const wp = Object.defineProperty(wrapPromise, '_checkLockKey', { value: (key) => lockCtx[key] });
413
- const wpVuePlugin = {
414
- install(appOrVue, key = '$wp') {
415
- if (appOrVue.config && 'globalProperties' in appOrVue.config) {
416
- appOrVue.config.globalProperties[key] = wrapPromise;
417
- }
418
- else {
419
- appOrVue.prototype[key] = wrapPromise;
420
- }
421
- }
422
- };
434
+ /** short for method `wrapPromise` */
435
+ const wp = wrapPromise;
423
436
 
424
437
  function safeJsonParse(json = '', faileValue) {
425
438
  try {
@@ -441,17 +454,23 @@ const isNullable = (value) => value === '' || value === undefined || value === n
441
454
  */
442
455
  const filterNullable = (obj, deep) => {
443
456
  const result = {};
444
- Object.keys(obj).forEach(key => {
445
- const value = obj[key];
446
- if (value !== '' && value !== undefined && value !== null) {
447
- 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
+ }
448
468
  }
449
469
  });
450
470
  return result;
451
471
  };
452
- const { toString } = Object.prototype;
453
472
  /**
454
- * 将对象中属性值为null的转换为undefined
473
+ * 将对象中属性值为null的转换为undefined,会返回一个浅拷贝的新对象
455
474
  * @param data 对象数据
456
475
  * @returns
457
476
  */
@@ -459,13 +478,15 @@ const switchNullToUndefined = (data) => {
459
478
  if (data === null) {
460
479
  return undefined;
461
480
  }
462
- if (Array.isArray(data)) {
481
+ if (isArr(data)) {
463
482
  return data.map(switchNullToUndefined);
464
483
  }
465
- else if (toString.call(data) === '[object Object]') {
466
- Object.keys(data).forEach((key) => {
467
- data[key] = switchNullToUndefined(data[key]);
484
+ else if (isObj(data)) {
485
+ const result = {};
486
+ objForEch(data, (key, value) => {
487
+ result[key] = switchNullToUndefined(value);
468
488
  });
489
+ return result;
469
490
  }
470
491
  return data;
471
492
  };
@@ -479,7 +500,7 @@ const formParamsSwitch = (formData, maps, options) => {
479
500
  const dateKeys = Object.keys(maps);
480
501
  const dateData = {};
481
502
  const restData = {};
482
- Object.keys(formData).forEach(key => {
503
+ objForEch(formData, (key) => {
483
504
  if (dateKeys.includes(key)) {
484
505
  dateData[key] = formData[key];
485
506
  }
@@ -492,7 +513,10 @@ const formParamsSwitch = (formData, maps, options) => {
492
513
  if (accessKeys.length === 0) {
493
514
  return formData;
494
515
  }
495
- const { filterNullable: filterNullableValue, dateFormat } = { filterNullable: true, ...options };
516
+ const { filterNullable: filterNullableValue, dateFormat } = {
517
+ filterNullable: true,
518
+ ...options
519
+ };
496
520
  const handleData = accessKeys.reduce((acc, key) => {
497
521
  const values = dateData[key];
498
522
  const mapValue = maps[key];
@@ -501,7 +525,7 @@ const formParamsSwitch = (formData, maps, options) => {
501
525
  }
502
526
  // 数组合并操作/取最后一位操作
503
527
  if (mapValue === 'join' || mapValue === 'pop') {
504
- if (Array.isArray(values) && values.length) {
528
+ if (isArr(values) && values.length) {
505
529
  acc[key] = mapValue === 'join' ? values.join(',') : values.slice(-1)[0];
506
530
  }
507
531
  }
@@ -512,8 +536,10 @@ const formParamsSwitch = (formData, maps, options) => {
512
536
  const [startKey, endKey, format] = mapValue;
513
537
  const [startValue, endValue] = values;
514
538
  Object.assign(acc, {
515
- [startKey]: dateFormat instanceof Function ? dateFormat(startValue, format) : startValue,
516
- [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
517
543
  });
518
544
  }
519
545
  return acc;
@@ -527,4 +553,306 @@ const formParamsSwitch = (formData, maps, options) => {
527
553
  /** 创建一个绑定了默认时间格式转换函数的formParamsSwitch函数 */
528
554
  const formParamsSwitchCreator = (dateFormat) => (formData, maps, options) => formParamsSwitch(formData, maps, { dateFormat, ...options });
529
555
 
530
- export { ChinaIdCardValid, array2tree, awaitWrapper, byteParse, byteStringify, checkoutBy, filterNullable, formParamsSwitch, formParamsSwitchCreator, formulaValidate, isNullable, mapToObject, objType, pickRenameKeys, safeJsonParse, switchNullToUndefined, tree2array, wp, wpVuePlugin };
556
+ const isStr = (val) => typeof val === 'string';
557
+ const NOMETHOD = Symbol('NOMETHOD');
558
+ /**
559
+ * 创建emitter形式的实例,可以通过实例封装事件对象,比如websocket,得到一个更便捷的方法,具体可参考page-communicate.js文件内容
560
+ * @param options 配置项
561
+ * @returns
562
+ */
563
+ function eventTargetEmitter(options) {
564
+ const watchers = new Map([[NOMETHOD, new Set()]]);
565
+ const { name: currentName, customHanlderCreator } = options || {};
566
+ const customHanlder = isFn(customHanlderCreator)
567
+ ? customHanlderCreator(watchers)
568
+ : null;
569
+ const splitRegExp = /\|-[a-z]+-\|/;
570
+ const listenerSafeRun = (listener, ...args) => {
571
+ try {
572
+ listener(...args);
573
+ }
574
+ catch (e) {
575
+ console.error(e);
576
+ }
577
+ };
578
+ const defaultHanlder = (payload) => {
579
+ const { method, data, originEmitterName: from, targetEmitterName: to } = payload || [];
580
+ if (method && typeof method === 'string') {
581
+ const matchListeners = [];
582
+ watchers.forEach((value, key) => {
583
+ if (typeof key === 'string' && key.startsWith(method)) {
584
+ const [, eFrom] = key.split(splitRegExp);
585
+ if (!eFrom || !from || eFrom === from) {
586
+ matchListeners.push(...value);
587
+ }
588
+ }
589
+ });
590
+ if (matchListeners.length &&
591
+ (!currentName || !to || currentName === to)) {
592
+ matchListeners.forEach((listener) => listenerSafeRun(listener, data));
593
+ }
594
+ }
595
+ const noMethodListeners = watchers.get(NOMETHOD);
596
+ if (noMethodListeners) {
597
+ noMethodListeners.forEach((listener) => listenerSafeRun(listener, data, payload));
598
+ }
599
+ };
600
+ const rootEventListener = isFn(customHanlder) ? customHanlder : defaultHanlder;
601
+ const getFullMethodName = (method, options) => {
602
+ const { limitFrom = '', namespace = '' } = options || {};
603
+ return (limitFrom || namespace) && typeof method === 'string'
604
+ ? `${method}|-from-|${limitFrom}|-ns-|${namespace}`
605
+ : method;
606
+ };
607
+ const on = (method, listener, options) => {
608
+ if (typeof method === 'symbol' && method !== NOMETHOD) {
609
+ return;
610
+ }
611
+ const trueMethod = getFullMethodName(method, options);
612
+ if (!watchers.has(trueMethod)) {
613
+ watchers.set(trueMethod, new Set());
614
+ }
615
+ const listeners = watchers.get(trueMethod);
616
+ listeners?.add(listener);
617
+ };
618
+ const off = (method, callback, options) => {
619
+ if (typeof method === 'symbol' && method !== NOMETHOD) {
620
+ return;
621
+ }
622
+ const { namespace } = options || {};
623
+ if (namespace && !method) {
624
+ watchers.forEach((_value, key) => {
625
+ if (typeof key === 'string' && key.endsWith(namespace)) {
626
+ watchers.delete(key);
627
+ }
628
+ });
629
+ return;
630
+ }
631
+ const trueMethod = getFullMethodName(method, options);
632
+ if (!callback) {
633
+ watchers.delete(trueMethod);
634
+ return;
635
+ }
636
+ watchers.get(trueMethod)?.delete(callback);
637
+ };
638
+ const removeAllListeners = () => {
639
+ watchers.clear();
640
+ };
641
+ const createPayload = (methodOrPayload, data, target) => {
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;
652
+ };
653
+ const emit = (...args) => {
654
+ const payload = createPayload(...args);
655
+ rootEventListener(payload);
656
+ };
657
+ /** 获取当前所有监听方法的方法名,默认仅返回函数名,设置all为true可以返回具体来源限制和命名空间字段 */
658
+ const getMethodNames = (all) => {
659
+ if (!all) {
660
+ const result = [];
661
+ watchers.forEach((_v, key) => isStr(key) && result.push(key.split(splitRegExp)));
662
+ return result;
663
+ }
664
+ const result = [];
665
+ watchers.forEach((_v, key) => isStr(key) && result.push(key));
666
+ return result;
667
+ };
668
+ const getListeners = (method, options) => {
669
+ if (typeof method === 'symbol') {
670
+ return method === NOMETHOD ? Array.from(watchers.get(NOMETHOD) || []) : [];
671
+ }
672
+ const trueMethod = getFullMethodName(method, options);
673
+ const listeners = watchers.get(trueMethod);
674
+ return listeners ? Array.from(listeners) : [];
675
+ };
676
+ return {
677
+ name: currentName,
678
+ rootEventListener,
679
+ on,
680
+ off,
681
+ emit,
682
+ createPayload,
683
+ removeAllListeners,
684
+ getMethodNames,
685
+ getListeners
686
+ };
687
+ }
688
+
689
+ /**
690
+ * 创建同源页面之间通信的封装实例,默认使用BroadcastChannel实现,在不支持的浏览器环境中会使用localstorage实现
691
+ * @param options 配置对象
692
+ * @returns
693
+ */
694
+ function pageCommunicate(options) {
695
+ const { messageHanlder, currentPage } = options || {};
696
+ const { emit, on, off, createPayload, removeAllListeners } = eventTargetEmitter({
697
+ name: currentPage,
698
+ customHanlderCreator: messageHanlder
699
+ });
700
+ const onMessage = (event) => emit(event.data);
701
+ let bc;
702
+ const ls = window.localStorage;
703
+ const channelName = 'PAGE_COMMUNICATE_CHANNEL';
704
+ if (typeof BroadcastChannel !== undefined) {
705
+ bc = new BroadcastChannel(channelName);
706
+ bc.addEventListener('message', onMessage);
707
+ }
708
+ else {
709
+ const onStorageMessage = () => {
710
+ const payload = safeJsonParse(ls.getItem(channelName) || '');
711
+ if (payload) {
712
+ emit(payload);
713
+ }
714
+ };
715
+ window.addEventListener('storage', onStorageMessage);
716
+ }
717
+ const send = (...args) => {
718
+ const payload = createPayload(...args);
719
+ if (bc) {
720
+ bc.postMessage(payload);
721
+ }
722
+ else {
723
+ const payloadWitchTs = JSON.stringify({ ...payload, ts: +new Date() });
724
+ ls.setItem(channelName, payloadWitchTs);
725
+ }
726
+ };
727
+ const destory = () => {
728
+ removeAllListeners();
729
+ if (bc) {
730
+ bc.close();
731
+ }
732
+ else {
733
+ ls.removeItem(channelName);
734
+ }
735
+ };
736
+ return { on, off, send, destory };
737
+ }
738
+
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 };