@wxhccc/es-util 1.4.1 → 1.6.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.d.ts CHANGED
@@ -3,3 +3,4 @@ export * from './validate';
3
3
  export * from './object-array';
4
4
  export * from './value-string-switch';
5
5
  export * from './promise';
6
+ export * from './optional';
package/dist/index.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.4.1
3
- * (c) 2021 wxhccc
2
+ * @wxhccc/es-util v1.6.0
3
+ * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  const { hasOwnProperty: hasOwnProperty$1 } = Object.prototype;
@@ -249,9 +249,53 @@ function byteStringify(byteNum, options) {
249
249
  function byteParse(byteStr, options = {}) {
250
250
  }
251
251
 
252
- const { hasOwnProperty, toString } = Object.prototype;
252
+ const modeIndexs = {
253
+ telphone: { startCharIndex: -8, endCharIndex: -5 },
254
+ idcard: { startCharIndex: -12, endCharIndex: -5 }
255
+ };
256
+ /**
257
+ * 对给定的字符串进行脱敏处理
258
+ * @param data 需要处理的字符串
259
+ * @param options 配置参数对象
260
+ * @returns
261
+ */
262
+ function maskData(data, options) {
263
+ if (typeof data !== 'string' || !data) {
264
+ return '';
265
+ }
266
+ const modeOpts = options && options.mode && modeIndexs[options.mode] ? modeIndexs[options.mode] : {};
267
+ const { maskWith, startCharIndex: start = 0, endCharIndex: end, startFrom, endUntil } = { maskWith: '*', ...modeOpts, ...options };
268
+ let handleData = data;
269
+ let beforeChars = '';
270
+ let afterChars = '';
271
+ const startFromIndex = startFrom ? data.indexOf(startFrom) : -1;
272
+ if (startFromIndex > -1) {
273
+ const index = startFromIndex + startFrom.length;
274
+ handleData = handleData.slice(index);
275
+ beforeChars = data.slice(0, index);
276
+ }
277
+ const endUtilIndex = endUntil ? data.lastIndexOf(endUntil) : -1;
278
+ if (endUtilIndex > -1) {
279
+ handleData = handleData.slice(0, endUtilIndex);
280
+ afterChars = data.slice(endUtilIndex);
281
+ }
282
+ const chars = handleData.split('');
283
+ const newChars = [beforeChars];
284
+ const charLen = chars.length;
285
+ const indexs = [start >= 0 ? start : charLen + start, end !== undefined ? (end >= 0 ? end : charLen + end) : charLen - 1];
286
+ let [startIdx, endIdx] = indexs;
287
+ endIdx = endIdx > 0 && endIdx < charLen ? endIdx : charLen - 1;
288
+ startIdx = startIdx >= 0 && startIdx <= endIdx ? startIdx : 0;
289
+ chars.forEach((char, idx) => {
290
+ newChars.push(idx >= startIdx && idx <= endIdx ? maskWith : char);
291
+ });
292
+ newChars.push(afterChars);
293
+ return newChars.join('');
294
+ }
295
+
296
+ const { hasOwnProperty, toString: toString$1 } = Object.prototype;
253
297
  const objType = (val) => {
254
- const typeKeys = toString.call(val).match(/^\[object (.*)\]$/);
298
+ const typeKeys = toString$1.call(val).match(/^\[object (.*)\]$/);
255
299
  return typeKeys ? typeKeys[1] : '';
256
300
  };
257
301
  /**
@@ -409,7 +453,7 @@ function wrapPromise(promise, wrapOrOptions) {
409
453
  }
410
454
  return corePromsie;
411
455
  }
412
- const wp = wrapPromise;
456
+ const wp = Object.defineProperty(wrapPromise, '_checkLockKey', { value: (key) => lockCtx[key] });
413
457
  const wpVuePlugin = {
414
458
  install(appOrVue, key = '$wp') {
415
459
  if (appOrVue.config && 'globalProperties' in appOrVue.config) {
@@ -421,4 +465,110 @@ const wpVuePlugin = {
421
465
  }
422
466
  };
423
467
 
424
- export { ChinaIdCardValid, array2tree, awaitWrapper, byteParse, byteStringify, checkoutBy, formulaValidate, mapToObject, objType, pickRenameKeys, tree2array, wp, wpVuePlugin };
468
+ function safeJsonParse(json = '', faileValue) {
469
+ try {
470
+ return JSON.parse(json);
471
+ }
472
+ catch (_e) {
473
+ return faileValue;
474
+ }
475
+ }
476
+ /**
477
+ * check value whether empty text
478
+ * 判断给定变量是否是字面量空值 */
479
+ const isNullable = (value) => value === '' || value === undefined || value === null;
480
+ /**
481
+ * 过滤对象中属性为空('' | undefined | null)的字段
482
+ * @param obj 给定对象
483
+ * @param deep 是否需要递归过滤
484
+ * @returns 过滤后的对象
485
+ */
486
+ const filterNullable = (obj, deep) => {
487
+ const result = {};
488
+ Object.keys(obj).forEach(key => {
489
+ const value = obj[key];
490
+ if (value !== '' && value !== undefined && value !== null) {
491
+ result[key] = deep && Object.prototype.toString.call(value) === '[object Object]' ? filterNullable(value) : value;
492
+ }
493
+ });
494
+ return result;
495
+ };
496
+ const { toString } = Object.prototype;
497
+ /**
498
+ * 将对象中属性值为null的转换为undefined
499
+ * @param data 对象数据
500
+ * @returns
501
+ */
502
+ const switchNullToUndefined = (data) => {
503
+ if (data === null) {
504
+ return undefined;
505
+ }
506
+ if (Array.isArray(data)) {
507
+ return data.map(switchNullToUndefined);
508
+ }
509
+ else if (toString.call(data) === '[object Object]') {
510
+ Object.keys(data).forEach((key) => {
511
+ data[key] = switchNullToUndefined(data[key]);
512
+ });
513
+ }
514
+ return data;
515
+ };
516
+ /**
517
+ * 将搜素条件里的数组字段转换为其他格式,通常用于搜索表单的字段转换
518
+ * @param formData 传入参数
519
+ * @param maps 转换的映射关系,eg:{ date: ['startTime', 'endTime'] }
520
+ * @param options 额外的配置参数
521
+ */
522
+ const formParamsSwitch = (formData, maps, options) => {
523
+ const dateKeys = Object.keys(maps);
524
+ const dateData = {};
525
+ const restData = {};
526
+ Object.keys(formData).forEach(key => {
527
+ if (dateKeys.includes(key)) {
528
+ dateData[key] = formData[key];
529
+ }
530
+ else {
531
+ restData[key] = formData[key];
532
+ }
533
+ });
534
+ const accessKeys = Object.keys(dateData);
535
+ // 如无需要转换的数据时,直接返回原对象
536
+ if (accessKeys.length === 0) {
537
+ return formData;
538
+ }
539
+ const { filterNullable: filterNullableValue, dateFormat } = { filterNullable: true, ...options };
540
+ const handleData = accessKeys.reduce((acc, key) => {
541
+ const values = dateData[key];
542
+ const mapValue = maps[key];
543
+ if (!values || !mapValue) {
544
+ return acc;
545
+ }
546
+ // 数组合并操作/取最后一位操作
547
+ if (mapValue === 'join' || mapValue === 'pop') {
548
+ if (Array.isArray(values) && values.length) {
549
+ acc[key] = mapValue === 'join' ? values.join(',') : values.slice(-1)[0];
550
+ }
551
+ }
552
+ else if (mapValue.length === 2 || mapValue.length === 3) {
553
+ if (!values || values.length !== 2) {
554
+ return acc;
555
+ }
556
+ const [startKey, endKey, format] = mapValue;
557
+ const [startValue, endValue] = values;
558
+ Object.assign(acc, {
559
+ [startKey]: dateFormat instanceof Function ? dateFormat(startValue, format) : startValue,
560
+ [endKey]: dateFormat instanceof Function ? dateFormat(endValue, format) : endValue
561
+ });
562
+ }
563
+ return acc;
564
+ }, {});
565
+ const result = {
566
+ ...restData,
567
+ ...handleData
568
+ };
569
+ return filterNullableValue ? filterNullable(result) : result;
570
+ };
571
+ /** 创建一个绑定了默认时间格式转换函数的formParamsSwitch函数 */
572
+ const formParamsSwitchCreator = (dateFormat) => (formData, maps, options) => formParamsSwitch(formData, maps, { dateFormat, ...options });
573
+
574
+ export { ChinaIdCardValid, array2tree, awaitWrapper, byteParse, byteStringify, checkoutBy, filterNullable, formParamsSwitch, formParamsSwitchCreator, formulaValidate, isNullable, mapToObject, maskData, objType, pickRenameKeys, safeJsonParse, switchNullToUndefined, tree2array, wp, wpVuePlugin };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.4.1
3
- * (c) 2021 wxhccc
2
+ * @wxhccc/es-util v1.6.0
3
+ * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
@@ -253,9 +253,53 @@ function byteStringify(byteNum, options) {
253
253
  function byteParse(byteStr, options = {}) {
254
254
  }
255
255
 
256
- const { hasOwnProperty, toString } = Object.prototype;
256
+ const modeIndexs = {
257
+ telphone: { startCharIndex: -8, endCharIndex: -5 },
258
+ idcard: { startCharIndex: -12, endCharIndex: -5 }
259
+ };
260
+ /**
261
+ * 对给定的字符串进行脱敏处理
262
+ * @param data 需要处理的字符串
263
+ * @param options 配置参数对象
264
+ * @returns
265
+ */
266
+ function maskData(data, options) {
267
+ if (typeof data !== 'string' || !data) {
268
+ return '';
269
+ }
270
+ const modeOpts = options && options.mode && modeIndexs[options.mode] ? modeIndexs[options.mode] : {};
271
+ const { maskWith, startCharIndex: start = 0, endCharIndex: end, startFrom, endUntil } = { maskWith: '*', ...modeOpts, ...options };
272
+ let handleData = data;
273
+ let beforeChars = '';
274
+ let afterChars = '';
275
+ const startFromIndex = startFrom ? data.indexOf(startFrom) : -1;
276
+ if (startFromIndex > -1) {
277
+ const index = startFromIndex + startFrom.length;
278
+ handleData = handleData.slice(index);
279
+ beforeChars = data.slice(0, index);
280
+ }
281
+ const endUtilIndex = endUntil ? data.lastIndexOf(endUntil) : -1;
282
+ if (endUtilIndex > -1) {
283
+ handleData = handleData.slice(0, endUtilIndex);
284
+ afterChars = data.slice(endUtilIndex);
285
+ }
286
+ const chars = handleData.split('');
287
+ const newChars = [beforeChars];
288
+ const charLen = chars.length;
289
+ const indexs = [start >= 0 ? start : charLen + start, end !== undefined ? (end >= 0 ? end : charLen + end) : charLen - 1];
290
+ let [startIdx, endIdx] = indexs;
291
+ endIdx = endIdx > 0 && endIdx < charLen ? endIdx : charLen - 1;
292
+ startIdx = startIdx >= 0 && startIdx <= endIdx ? startIdx : 0;
293
+ chars.forEach((char, idx) => {
294
+ newChars.push(idx >= startIdx && idx <= endIdx ? maskWith : char);
295
+ });
296
+ newChars.push(afterChars);
297
+ return newChars.join('');
298
+ }
299
+
300
+ const { hasOwnProperty, toString: toString$1 } = Object.prototype;
257
301
  const objType = (val) => {
258
- const typeKeys = toString.call(val).match(/^\[object (.*)\]$/);
302
+ const typeKeys = toString$1.call(val).match(/^\[object (.*)\]$/);
259
303
  return typeKeys ? typeKeys[1] : '';
260
304
  };
261
305
  /**
@@ -413,7 +457,7 @@ function wrapPromise(promise, wrapOrOptions) {
413
457
  }
414
458
  return corePromsie;
415
459
  }
416
- const wp = wrapPromise;
460
+ const wp = Object.defineProperty(wrapPromise, '_checkLockKey', { value: (key) => lockCtx[key] });
417
461
  const wpVuePlugin = {
418
462
  install(appOrVue, key = '$wp') {
419
463
  if (appOrVue.config && 'globalProperties' in appOrVue.config) {
@@ -425,16 +469,129 @@ const wpVuePlugin = {
425
469
  }
426
470
  };
427
471
 
472
+ function safeJsonParse(json = '', faileValue) {
473
+ try {
474
+ return JSON.parse(json);
475
+ }
476
+ catch (_e) {
477
+ return faileValue;
478
+ }
479
+ }
480
+ /**
481
+ * check value whether empty text
482
+ * 判断给定变量是否是字面量空值 */
483
+ const isNullable = (value) => value === '' || value === undefined || value === null;
484
+ /**
485
+ * 过滤对象中属性为空('' | undefined | null)的字段
486
+ * @param obj 给定对象
487
+ * @param deep 是否需要递归过滤
488
+ * @returns 过滤后的对象
489
+ */
490
+ const filterNullable = (obj, deep) => {
491
+ const result = {};
492
+ Object.keys(obj).forEach(key => {
493
+ const value = obj[key];
494
+ if (value !== '' && value !== undefined && value !== null) {
495
+ result[key] = deep && Object.prototype.toString.call(value) === '[object Object]' ? filterNullable(value) : value;
496
+ }
497
+ });
498
+ return result;
499
+ };
500
+ const { toString } = Object.prototype;
501
+ /**
502
+ * 将对象中属性值为null的转换为undefined
503
+ * @param data 对象数据
504
+ * @returns
505
+ */
506
+ const switchNullToUndefined = (data) => {
507
+ if (data === null) {
508
+ return undefined;
509
+ }
510
+ if (Array.isArray(data)) {
511
+ return data.map(switchNullToUndefined);
512
+ }
513
+ else if (toString.call(data) === '[object Object]') {
514
+ Object.keys(data).forEach((key) => {
515
+ data[key] = switchNullToUndefined(data[key]);
516
+ });
517
+ }
518
+ return data;
519
+ };
520
+ /**
521
+ * 将搜素条件里的数组字段转换为其他格式,通常用于搜索表单的字段转换
522
+ * @param formData 传入参数
523
+ * @param maps 转换的映射关系,eg:{ date: ['startTime', 'endTime'] }
524
+ * @param options 额外的配置参数
525
+ */
526
+ const formParamsSwitch = (formData, maps, options) => {
527
+ const dateKeys = Object.keys(maps);
528
+ const dateData = {};
529
+ const restData = {};
530
+ Object.keys(formData).forEach(key => {
531
+ if (dateKeys.includes(key)) {
532
+ dateData[key] = formData[key];
533
+ }
534
+ else {
535
+ restData[key] = formData[key];
536
+ }
537
+ });
538
+ const accessKeys = Object.keys(dateData);
539
+ // 如无需要转换的数据时,直接返回原对象
540
+ if (accessKeys.length === 0) {
541
+ return formData;
542
+ }
543
+ const { filterNullable: filterNullableValue, dateFormat } = { filterNullable: true, ...options };
544
+ const handleData = accessKeys.reduce((acc, key) => {
545
+ const values = dateData[key];
546
+ const mapValue = maps[key];
547
+ if (!values || !mapValue) {
548
+ return acc;
549
+ }
550
+ // 数组合并操作/取最后一位操作
551
+ if (mapValue === 'join' || mapValue === 'pop') {
552
+ if (Array.isArray(values) && values.length) {
553
+ acc[key] = mapValue === 'join' ? values.join(',') : values.slice(-1)[0];
554
+ }
555
+ }
556
+ else if (mapValue.length === 2 || mapValue.length === 3) {
557
+ if (!values || values.length !== 2) {
558
+ return acc;
559
+ }
560
+ const [startKey, endKey, format] = mapValue;
561
+ const [startValue, endValue] = values;
562
+ Object.assign(acc, {
563
+ [startKey]: dateFormat instanceof Function ? dateFormat(startValue, format) : startValue,
564
+ [endKey]: dateFormat instanceof Function ? dateFormat(endValue, format) : endValue
565
+ });
566
+ }
567
+ return acc;
568
+ }, {});
569
+ const result = {
570
+ ...restData,
571
+ ...handleData
572
+ };
573
+ return filterNullableValue ? filterNullable(result) : result;
574
+ };
575
+ /** 创建一个绑定了默认时间格式转换函数的formParamsSwitch函数 */
576
+ const formParamsSwitchCreator = (dateFormat) => (formData, maps, options) => formParamsSwitch(formData, maps, { dateFormat, ...options });
577
+
428
578
  exports.ChinaIdCardValid = ChinaIdCardValid;
429
579
  exports.array2tree = array2tree;
430
580
  exports.awaitWrapper = awaitWrapper;
431
581
  exports.byteParse = byteParse;
432
582
  exports.byteStringify = byteStringify;
433
583
  exports.checkoutBy = checkoutBy;
584
+ exports.filterNullable = filterNullable;
585
+ exports.formParamsSwitch = formParamsSwitch;
586
+ exports.formParamsSwitchCreator = formParamsSwitchCreator;
434
587
  exports.formulaValidate = formulaValidate;
588
+ exports.isNullable = isNullable;
435
589
  exports.mapToObject = mapToObject;
590
+ exports.maskData = maskData;
436
591
  exports.objType = objType;
437
592
  exports.pickRenameKeys = pickRenameKeys;
593
+ exports.safeJsonParse = safeJsonParse;
594
+ exports.switchNullToUndefined = switchNullToUndefined;
438
595
  exports.tree2array = tree2array;
439
596
  exports.wp = wp;
440
597
  exports.wpVuePlugin = wpVuePlugin;
package/dist/index.min.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.4.1
3
- * (c) 2021 wxhccc
2
+ * @wxhccc/es-util v1.6.0
3
+ * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
6
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Smartfetch={})}(this,(function(e){"use strict";const{hasOwnProperty:t}=Object.prototype;function n(e,t=[]){return{[e]:t}}const r=/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i;const{hasOwnProperty:i,toString:c}=Object.prototype,o=e=>{const t=c.call(e).match(/^\[object (.*)\]$/);return t?t[1]:""};async function a(e){try{return[null,await e]}catch(e){return[e,void 0]}}const s={};function l(e,t){const n=function(e){return e?e._isVue||e.$&&e.$.vnode?"vue":"setState"in e?"react":"unknown":"unknown"}(this),r="unknown"!==n,c=r?this:s,l="react"===n?"state":"",u=l?c[l]:c,{wrap:p,lock:f,syncRefHandle:y,manualUnlock:d}="boolean"==typeof t?{wrap:t}:{...t};let b,h,g=[],j=!1,m=!1;const B=(e,t)=>!!e&&i.call(e,t),O=e=>"Object"===o(e),x=e=>{g.length?r?((e,t,r)=>{if("vue"===n&&c.$set&&!B(e,t[0]))return;const{$set:i=((e,t,n)=>{e[t]=n})}=c,o="react"===n,a=o?{...e}:e;let s=a,l=!1;for(let e=0;e<t.length;e++){const n=t[e],c=B(s,n);if(e===t.length-1){const e="boolean"==typeof s[n];l=!c||e,l&&i(s,n,r)}else{if(!c&&i(s,n,{}),!O(s[n]))break;o&&(s[n]={...s[n]}),s=s[n]}}o&&l&&c.setState({[t[0]]:a[t[0]]})})(u,g,e):s[f]=e:(h&&(h[0][h[1]]=e),b&&b(e))},A=()=>h?h[0][h[1]]:r||"string"!=typeof f?((e,t)=>{let n=!1;if(e&&O(e)&&Array.isArray(t)&&t.length){let r=e;for(let e=0;e<t.length;e++){const i=t[e];if("object"!=typeof r||!B(r,i))break;r=r[i],e===t.length-1&&(n="boolean"==typeof r&&r)}}return n})(u,g):u[f];if(f){const e=e=>Array.isArray(e)&&2===e.length;"string"==typeof f?g=f.split("."):e(f)?h=f:"function"==typeof f&&(b=f,e(y)&&(h=y)),j=g.length>0||!!h||!!b,j&&(m=A())}let K;K="function"==typeof e?m?(()=>{const e=Promise.resolve(void 0);return Object.assign(e,{then(...t){const[n]=t;return 2===t.length&&"function"==typeof n?n(void 0):e},catch:t=>e,finally:()=>e})})():p?a(e()):e():p?a(e):e;const M=()=>x(!1);return Object.defineProperties(K,{__lockValue:{get:A},_checkLockKey:{value:e=>s[e]},unlock:{value:M}}),j&&!m&&(x(!0),!d&&K.finally(M)),K}const u=l,p={install(e,t="$wp"){e.config&&"globalProperties"in e.config?e.config.globalProperties[t]=l:e.prototype[t]=l}};e.ChinaIdCardValid=function(e){const t=e.toString().toUpperCase();return r.test(t)&&["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"].includes(t.substr(0,2))&&(()=>{if(18===t.length){const e=t.split(""),n=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2],r=[1,0,"X",9,8,7,6,5,4,3,2];let i=0,c=0,o=0;for(let t=0;t<17;t++)c=parseInt(e[t]),o=n[t],i+=c*o;return r[i%11].toString()===e[17]}return!0})()},e.array2tree=function(e,r={}){const{primaryKey:i,parentKey:c,childrenKey:o,createRoot:a,parentRefKey:s}=Object.assign({primaryKey:"id",parentKey:"pid",childrenKey:"children",createRoot:!1,parentRefKey:!1},r),l=s&&("string"==typeof s?s:"_parent");let u={},p=[];return Array.isArray(e)&&e.forEach((e=>{!t.call(u,e[i])&&(u[e[i]]=Object.assign({},e,n(o))),t.call(u,e[c])&&u[e[c]][o].push(Object.assign(u[e[i]],l?{[l]:u[e[c]]}:{})),!e[c]&&p.push(u[e[i]])})),"function"==typeof a?a(p):a?{[o]:p}:p},e.awaitWrapper=a,e.byteParse=function(e,t={}){},e.byteStringify=function(e,t){const n=Object.assign({standard:"jedec",unitLvl:"auto",precision:1,detail:!1},t),{standard:r,unitLvl:i,precision:c,detail:o}=n;let a=parseFloat(e);if(!Number.isFinite(a))return;const s=a<0?-1:1;a=Math.abs(a);const{base:l,unitMap:u}=((e,t)=>{const n={B:{expMax:0,units:{metric:"B",iec:"B",jedec:"B"}},K:{expMax:1,units:{metric:"kB",iec:"KiB",jedec:"KB"}},M:{expMax:2,units:{metric:"MB",iec:"MiB",jedec:"MB"}},G:{expMax:3,units:{metric:"GB",iec:"GiB",jedec:"GB"}},T:{expMax:4,units:{metric:"TB",iec:"TiB",jedec:"TB"}},P:{expMax:5,units:{metric:"PB",iec:"PiB",jedec:"PB"}},E:{expMax:6,units:{metric:"EB",iec:"EiB",jedec:"EB"}},Z:{expMax:7,units:{metric:"ZB",iec:"ZiB",jedec:"ZB"}},Y:{expMax:8,units:{metric:"YB",iec:"YiB",jedec:"YB"}}},r={metric:1e3,iec:1024,jedec:1024};return{base:r[e]||r.jedec,unitMap:n[t]||Object.values(n)}})(r,i),p=e=>Number.isInteger(e)?e:e.toFixed(c);let f="",y=0;if(Array.isArray(u))u.some((e=>{const t=Math.pow(l,e.expMax),n=a/t;return!(n>l)&&(f=e.units[r],y=p(n*s),!0)}));else{const e=Math.pow(l,u.expMax);f=u.units[r];y=p(a/e*s)}return o?{value:y,unit:f}:`${y} ${f}`},e.checkoutBy=function(e,t,n){return e instanceof Object?Array.isArray(t)?t.map((t=>e[t])):t&&t instanceof Object?Object.keys(t).map((r=>e[r]instanceof Object&&t[r]instanceof Object?n?n({},e[r],t[r]):Object.assign({},e[r],t[r]):t[r]||e[r])):Object.values(e):[]},e.formulaValidate=function(e,t){return e=e.replace(/\s/g,""),!/[+\-*/]{2,}/.test(e)&&!/\(\)/.test(e)&&!/\([+\-*/]/.test(e)&&!/[+\-*/]\)/.test(e)&&!/[^+\-*/]\(/.test(e)&&!/\)[^+\-*/]/.test(e)&&(()=>{let t=[];for(let n,r=0;r<e.length;r++)if(n=e.charAt(r),"("===n)t.push("(");else if(")"===n){if(!(t.length>0))return!1;t.pop()}return!t.length})()&&(!Array.isArray(t)||(n=t,e.replace(/[()+\-*/]{1,}/g,"`").split("`").every((e=>!/[A-Z]/i.test(e)||n.includes(e)))));var n},e.mapToObject=function(e,t="key",n="value"){let r={};return Array.isArray(e)&&t&&n&&[t,n].every((e=>["string","function"].includes(typeof e)))&&e.forEach(((e,i)=>{const c="string"==typeof t?e[t]:t(e,i),o="string"==typeof n?e[n]:n(e,i);["string","number"].includes(typeof c)&&(r[c]=o)})),r},e.objType=o,e.pickRenameKeys=function(e,t){if(!(e&&e instanceof Object&&t&&t instanceof Object))return;let n={};for(let r in e)r in t&&(n[t[r]]=e[r]);return n},e.tree2array=function(e,t={}){const{primaryKey:r,parentKey:i,childrenKey:c,hasParentKey:o,returnObject:a}=Object.assign({hasParentKey:!0,primaryKey:"id",parentKey:"pid",childrenKey:"children",returnObject:!1},t);let s=a?{}:[];return Array.isArray(e)||"object"==typeof e?(function e(t,n,l=!1){let u=o?{}:{[i]:n};if(!l){const e=Object.assign(u,function(e,t){let n={};for(let r in e)r!==t&&(n[r]=e[r]);return n}(t,c));a?s[t[r]]=e:s.push(e)}Array.isArray(t[c])&&t[c].length&&t[c].forEach((n=>e(n,t[r])))}(Array.isArray(e)?n(c,e):e,null,!0),s):s},e.wp=u,e.wpVuePlugin=p,Object.defineProperty(e,"__esModule",{value:!0})}));
6
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Smartfetch={})}(this,(function(e){"use strict";const{hasOwnProperty:t}=Object.prototype;function n(e,t=[]){return{[e]:t}}const r=/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i;const i={telphone:{startCharIndex:-8,endCharIndex:-5},idcard:{startCharIndex:-12,endCharIndex:-5}};const{hasOwnProperty:c,toString:o}=Object.prototype,s=e=>{const t=o.call(e).match(/^\[object (.*)\]$/);return t?t[1]:""};async function a(e){try{return[null,await e]}catch(e){return[e,void 0]}}const l={};function u(e,t){const n=function(e){return e?e._isVue||e.$&&e.$.vnode?"vue":"setState"in e?"react":"unknown":"unknown"}(this),r="unknown"!==n,i=r?this:l,o="react"===n?"state":"",u=o?i[o]:i,{wrap:f,lock:p,syncRefHandle:y,manualUnlock:d}="boolean"==typeof t?{wrap:t}:{...t};let h,b,j=[],g=!1,m=!1;const O=(e,t)=>!!e&&c.call(e,t),x=e=>"Object"===s(e),B=e=>{j.length?r?((e,t,r)=>{if("vue"===n&&i.$set&&!O(e,t[0]))return;const{$set:c=((e,t,n)=>{e[t]=n})}=i,o="react"===n,s=o?{...e}:e;let a=s,l=!1;for(let e=0;e<t.length;e++){const n=t[e],i=O(a,n);if(e===t.length-1){const e="boolean"==typeof a[n];l=!i||e,l&&c(a,n,r)}else{if(!i&&c(a,n,{}),!x(a[n]))break;o&&(a[n]={...a[n]}),a=a[n]}}o&&l&&i.setState({[t[0]]:s[t[0]]})})(u,j,e):l[p]=e:(b&&(b[0][b[1]]=e),h&&h(e))},k=()=>b?b[0][b[1]]:r||"string"!=typeof p?((e,t)=>{let n=!1;if(e&&x(e)&&Array.isArray(t)&&t.length){let r=e;for(let e=0;e<t.length;e++){const i=t[e];if("object"!=typeof r||!O(r,i))break;r=r[i],e===t.length-1&&(n="boolean"==typeof r&&r)}}return n})(u,j):u[p];if(p){const e=e=>Array.isArray(e)&&2===e.length;"string"==typeof p?j=p.split("."):e(p)?b=p:"function"==typeof p&&(h=p,e(y)&&(b=y)),g=j.length>0||!!b||!!h,g&&(m=k())}let A;A="function"==typeof e?m?(()=>{const e=Promise.resolve(void 0);return Object.assign(e,{then(...t){const[n]=t;return 2===t.length&&"function"==typeof n?n(void 0):e},catch:t=>e,finally:()=>e})})():f?a(e()):e():f?a(e):e;const K=()=>B(!1);return Object.defineProperties(A,{__lockValue:{get:k},_checkLockKey:{value:e=>l[e]},unlock:{value:K}}),g&&!m&&(B(!0),!d&&A.finally(K)),A}const f=Object.defineProperty(u,"_checkLockKey",{value:e=>l[e]}),p={install(e,t="$wp"){e.config&&"globalProperties"in e.config?e.config.globalProperties[t]=u:e.prototype[t]=u}};const y=(e,t)=>{const n={};return Object.keys(e).forEach((r=>{const i=e[r];""!==i&&null!=i&&(n[r]=t&&"[object Object]"===Object.prototype.toString.call(i)?y(i):i)})),n},{toString:d}=Object.prototype,h=e=>{if(null!==e)return Array.isArray(e)?e.map(h):("[object Object]"===d.call(e)&&Object.keys(e).forEach((t=>{e[t]=h(e[t])})),e)},b=(e,t,n)=>{const r=Object.keys(t),i={},c={};Object.keys(e).forEach((t=>{r.includes(t)?i[t]=e[t]:c[t]=e[t]}));const o=Object.keys(i);if(0===o.length)return e;const{filterNullable:s,dateFormat:a}={filterNullable:!0,...n},l=o.reduce(((e,n)=>{const r=i[n],c=t[n];if(!r||!c)return e;if("join"===c||"pop"===c)Array.isArray(r)&&r.length&&(e[n]="join"===c?r.join(","):r.slice(-1)[0]);else if(2===c.length||3===c.length){if(!r||2!==r.length)return e;const[t,n,i]=c,[o,s]=r;Object.assign(e,{[t]:a instanceof Function?a(o,i):o,[n]:a instanceof Function?a(s,i):s})}return e}),{}),u={...c,...l};return s?y(u):u};e.ChinaIdCardValid=function(e){const t=e.toString().toUpperCase();return r.test(t)&&["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"].includes(t.substr(0,2))&&(()=>{if(18===t.length){const e=t.split(""),n=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2],r=[1,0,"X",9,8,7,6,5,4,3,2];let i=0,c=0,o=0;for(let t=0;t<17;t++)c=parseInt(e[t]),o=n[t],i+=c*o;return r[i%11].toString()===e[17]}return!0})()},e.array2tree=function(e,r={}){const{primaryKey:i,parentKey:c,childrenKey:o,createRoot:s,parentRefKey:a}=Object.assign({primaryKey:"id",parentKey:"pid",childrenKey:"children",createRoot:!1,parentRefKey:!1},r),l=a&&("string"==typeof a?a:"_parent");let u={},f=[];return Array.isArray(e)&&e.forEach((e=>{!t.call(u,e[i])&&(u[e[i]]=Object.assign({},e,n(o))),t.call(u,e[c])&&u[e[c]][o].push(Object.assign(u[e[i]],l?{[l]:u[e[c]]}:{})),!e[c]&&f.push(u[e[i]])})),"function"==typeof s?s(f):s?{[o]:f}:f},e.awaitWrapper=a,e.byteParse=function(e,t={}){},e.byteStringify=function(e,t){const n=Object.assign({standard:"jedec",unitLvl:"auto",precision:1,detail:!1},t),{standard:r,unitLvl:i,precision:c,detail:o}=n;let s=parseFloat(e);if(!Number.isFinite(s))return;const a=s<0?-1:1;s=Math.abs(s);const{base:l,unitMap:u}=((e,t)=>{const n={B:{expMax:0,units:{metric:"B",iec:"B",jedec:"B"}},K:{expMax:1,units:{metric:"kB",iec:"KiB",jedec:"KB"}},M:{expMax:2,units:{metric:"MB",iec:"MiB",jedec:"MB"}},G:{expMax:3,units:{metric:"GB",iec:"GiB",jedec:"GB"}},T:{expMax:4,units:{metric:"TB",iec:"TiB",jedec:"TB"}},P:{expMax:5,units:{metric:"PB",iec:"PiB",jedec:"PB"}},E:{expMax:6,units:{metric:"EB",iec:"EiB",jedec:"EB"}},Z:{expMax:7,units:{metric:"ZB",iec:"ZiB",jedec:"ZB"}},Y:{expMax:8,units:{metric:"YB",iec:"YiB",jedec:"YB"}}},r={metric:1e3,iec:1024,jedec:1024};return{base:r[e]||r.jedec,unitMap:n[t]||Object.values(n)}})(r,i),f=e=>Number.isInteger(e)?e:e.toFixed(c);let p="",y=0;if(Array.isArray(u))u.some((e=>{const t=Math.pow(l,e.expMax),n=s/t;return!(n>l)&&(p=e.units[r],y=f(n*a),!0)}));else{const e=Math.pow(l,u.expMax);p=u.units[r];y=f(s/e*a)}return o?{value:y,unit:p}:`${y} ${p}`},e.checkoutBy=function(e,t,n){return e instanceof Object?Array.isArray(t)?t.map((t=>e[t])):t&&t instanceof Object?Object.keys(t).map((r=>e[r]instanceof Object&&t[r]instanceof Object?n?n({},e[r],t[r]):Object.assign({},e[r],t[r]):t[r]||e[r])):Object.values(e):[]},e.filterNullable=y,e.formParamsSwitch=b,e.formParamsSwitchCreator=e=>(t,n,r)=>b(t,n,{dateFormat:e,...r}),e.formulaValidate=function(e,t){return e=e.replace(/\s/g,""),!/[+\-*/]{2,}/.test(e)&&!/\(\)/.test(e)&&!/\([+\-*/]/.test(e)&&!/[+\-*/]\)/.test(e)&&!/[^+\-*/]\(/.test(e)&&!/\)[^+\-*/]/.test(e)&&(()=>{let t=[];for(let n,r=0;r<e.length;r++)if(n=e.charAt(r),"("===n)t.push("(");else if(")"===n){if(!(t.length>0))return!1;t.pop()}return!t.length})()&&(!Array.isArray(t)||(n=t,e.replace(/[()+\-*/]{1,}/g,"`").split("`").every((e=>!/[A-Z]/i.test(e)||n.includes(e)))));var n},e.isNullable=e=>""===e||null==e,e.mapToObject=function(e,t="key",n="value"){let r={};return Array.isArray(e)&&t&&n&&[t,n].every((e=>["string","function"].includes(typeof e)))&&e.forEach(((e,i)=>{const c="string"==typeof t?e[t]:t(e,i),o="string"==typeof n?e[n]:n(e,i);["string","number"].includes(typeof c)&&(r[c]=o)})),r},e.maskData=function(e,t){if("string"!=typeof e||!e)return"";const n=t&&t.mode&&i[t.mode]?i[t.mode]:{},{maskWith:r,startCharIndex:c=0,endCharIndex:o,startFrom:s,endUntil:a}={maskWith:"*",...n,...t};let l=e,u="",f="";const p=s?e.indexOf(s):-1;if(p>-1){const t=p+s.length;l=l.slice(t),u=e.slice(0,t)}const y=a?e.lastIndexOf(a):-1;y>-1&&(l=l.slice(0,y),f=e.slice(y));const d=l.split(""),h=[u],b=d.length,j=[c>=0?c:b+c,void 0!==o?o>=0?o:b+o:b-1];let[g,m]=j;return m=m>0&&m<b?m:b-1,g=g>=0&&g<=m?g:0,d.forEach(((e,t)=>{h.push(t>=g&&t<=m?r:e)})),h.push(f),h.join("")},e.objType=s,e.pickRenameKeys=function(e,t){if(!(e&&e instanceof Object&&t&&t instanceof Object))return;let n={};for(let r in e)r in t&&(n[t[r]]=e[r]);return n},e.safeJsonParse=function(e="",t){try{return JSON.parse(e)}catch(e){return t}},e.switchNullToUndefined=h,e.tree2array=function(e,t={}){const{primaryKey:r,parentKey:i,childrenKey:c,hasParentKey:o,returnObject:s}=Object.assign({hasParentKey:!0,primaryKey:"id",parentKey:"pid",childrenKey:"children",returnObject:!1},t);let a=s?{}:[];return Array.isArray(e)||"object"==typeof e?(function e(t,n,l=!1){let u=o?{}:{[i]:n};if(!l){const e=Object.assign(u,function(e,t){let n={};for(let r in e)r!==t&&(n[r]=e[r]);return n}(t,c));s?a[t[r]]=e:a.push(e)}Array.isArray(t[c])&&t[c].length&&t[c].forEach((n=>e(n,t[r])))}(Array.isArray(e)?n(c,e):e,null,!0),a):a},e.wp=f,e.wpVuePlugin=p,Object.defineProperty(e,"__esModule",{value:!0})}));
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.4.1
3
- * (c) 2021 wxhccc
2
+ * @wxhccc/es-util v1.6.0
3
+ * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
@@ -0,0 +1,50 @@
1
+ declare type AnyObject = Record<string | number, any>;
2
+ /**
3
+ * JSON.parse string safely
4
+ * @param json string
5
+ * @param faileValue any
6
+ * @returns any
7
+ */
8
+ export declare function safeJsonParse<T = AnyObject>(json?: string): T | undefined;
9
+ export declare function safeJsonParse<T = AnyObject>(json: string | undefined, faileValue: T): T;
10
+ /**
11
+ * check value whether empty text
12
+ * 判断给定变量是否是字面量空值 */
13
+ export declare const isNullable: (value: unknown) => value is "" | null | undefined;
14
+ /**
15
+ * 过滤对象中属性为空('' | undefined | null)的字段
16
+ * @param obj 给定对象
17
+ * @param deep 是否需要递归过滤
18
+ * @returns 过滤后的对象
19
+ */
20
+ export declare const filterNullable: <T extends AnyObject>(obj: T, deep?: boolean | undefined) => T;
21
+ /**
22
+ * 将对象中属性值为null的转换为undefined
23
+ * @param data 对象数据
24
+ * @returns
25
+ */
26
+ export declare const switchNullToUndefined: (data: any) => any;
27
+ /**
28
+ * 参数转换规则的配置对象
29
+ * 值可以是时间范围转换所需的开始,结束时间字段的名称,或者需要进行拼接的数组
30
+ */
31
+ export declare type ParamsSwitchMaps<DK extends string = string, RK extends string = string> = Record<DK, [
32
+ RK,
33
+ RK
34
+ ] | [RK, RK, string] | 'join' | 'pop'>;
35
+ export declare type DateFormat = (date: any, format?: string) => string;
36
+ /**
37
+ * 将搜素条件里的数组字段转换为其他格式,通常用于搜索表单的字段转换
38
+ * @param formData 传入参数
39
+ * @param maps 转换的映射关系,eg:{ date: ['startTime', 'endTime'] }
40
+ * @param options 额外的配置参数
41
+ */
42
+ export declare const formParamsSwitch: <R extends AnyObject = AnyObject, T extends AnyObject = AnyObject>(formData: T, maps: Partial<ParamsSwitchMaps<Exclude<keyof T, number | symbol>, Exclude<keyof R, number | symbol>>>, options?: {
43
+ /** 是否需要过滤空数据 */
44
+ filterNullable?: boolean | undefined;
45
+ /** 时间格式换函数 */
46
+ dateFormat?: DateFormat | undefined;
47
+ } | undefined) => R;
48
+ /** 创建一个绑定了默认时间格式转换函数的formParamsSwitch函数 */
49
+ export declare const formParamsSwitchCreator: (dateFormat: DateFormat) => typeof formParamsSwitch;
50
+ export {};
package/dist/promise.d.ts CHANGED
@@ -34,7 +34,10 @@ declare function wrapPromise<T>(this: any, promise: WpPromise<T>, options?: WpOp
34
34
  declare function wrapPromise<T>(this: any, promise: WpPromise<T>, options?: WpOptions & {
35
35
  wrap: true;
36
36
  }): WpArrReturn<T>;
37
- export declare const wp: typeof wrapPromise;
37
+ declare type WP = typeof wrapPromise & {
38
+ _checkLockKey: (key: string) => boolean;
39
+ };
40
+ export declare const wp: WP;
38
41
  export declare const wpVuePlugin: {
39
42
  install(appOrVue: any, key?: string): void;
40
43
  };
package/dist/promise.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.4.1
3
- * (c) 2021 wxhccc
2
+ * @wxhccc/es-util v1.6.0
3
+ * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
@@ -167,7 +167,7 @@ function wrapPromise(promise, wrapOrOptions) {
167
167
  }
168
168
  return corePromsie;
169
169
  }
170
- const wp = wrapPromise;
170
+ const wp = Object.defineProperty(wrapPromise, '_checkLockKey', { value: (key) => lockCtx[key] });
171
171
  const wpVuePlugin = {
172
172
  install(appOrVue, key = '$wp') {
173
173
  if (appOrVue.config && 'globalProperties' in appOrVue.config) {
package/dist/validate.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.4.1
3
- * (c) 2021 wxhccc
2
+ * @wxhccc/es-util v1.6.0
3
+ * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
@@ -1 +1,2 @@
1
1
  export * from './byte-string';
2
+ export * from './mask-data';
@@ -0,0 +1,22 @@
1
+ interface MaskDataOptions {
2
+ /** 替换的字符,默认为* */
3
+ maskWith?: string;
4
+ /** 起始字符索引,为负数时从字符串结尾起倒数第几个数开始 */
5
+ startCharIndex?: number;
6
+ /** 结束字符索引,包含在处理字符内,缺省时会替换到字符串结尾,为负数时从字符串结尾起倒数第几个数开始 */
7
+ endCharIndex?: number;
8
+ /** 待处理字符串起始处理字符(串),不包含在待处理片段内 */
9
+ startFrom?: string;
10
+ /** 待处理字符串结束处理字符(串),不包含在待处理片段内 */
11
+ endUntil?: string;
12
+ /** 内置的默认的的处理模式,会预设一些属性值,属性值可以被覆盖 */
13
+ mode?: 'telphone' | 'idcard';
14
+ }
15
+ /**
16
+ * 对给定的字符串进行脱敏处理
17
+ * @param data 需要处理的字符串
18
+ * @param options 配置参数对象
19
+ * @returns
20
+ */
21
+ export declare function maskData(data: string, options?: MaskDataOptions): string;
22
+ export {};
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.4.1
3
- * (c) 2021 wxhccc
2
+ * @wxhccc/es-util v1.6.0
3
+ * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
@@ -67,5 +67,50 @@ function byteStringify(byteNum, options) {
67
67
  function byteParse(byteStr, options = {}) {
68
68
  }
69
69
 
70
+ const modeIndexs = {
71
+ telphone: { startCharIndex: -8, endCharIndex: -5 },
72
+ idcard: { startCharIndex: -12, endCharIndex: -5 }
73
+ };
74
+ /**
75
+ * 对给定的字符串进行脱敏处理
76
+ * @param data 需要处理的字符串
77
+ * @param options 配置参数对象
78
+ * @returns
79
+ */
80
+ function maskData(data, options) {
81
+ if (typeof data !== 'string' || !data) {
82
+ return '';
83
+ }
84
+ const modeOpts = options && options.mode && modeIndexs[options.mode] ? modeIndexs[options.mode] : {};
85
+ const { maskWith, startCharIndex: start = 0, endCharIndex: end, startFrom, endUntil } = { maskWith: '*', ...modeOpts, ...options };
86
+ let handleData = data;
87
+ let beforeChars = '';
88
+ let afterChars = '';
89
+ const startFromIndex = startFrom ? data.indexOf(startFrom) : -1;
90
+ if (startFromIndex > -1) {
91
+ const index = startFromIndex + startFrom.length;
92
+ handleData = handleData.slice(index);
93
+ beforeChars = data.slice(0, index);
94
+ }
95
+ const endUtilIndex = endUntil ? data.lastIndexOf(endUntil) : -1;
96
+ if (endUtilIndex > -1) {
97
+ handleData = handleData.slice(0, endUtilIndex);
98
+ afterChars = data.slice(endUtilIndex);
99
+ }
100
+ const chars = handleData.split('');
101
+ const newChars = [beforeChars];
102
+ const charLen = chars.length;
103
+ const indexs = [start >= 0 ? start : charLen + start, end !== undefined ? (end >= 0 ? end : charLen + end) : charLen - 1];
104
+ let [startIdx, endIdx] = indexs;
105
+ endIdx = endIdx > 0 && endIdx < charLen ? endIdx : charLen - 1;
106
+ startIdx = startIdx >= 0 && startIdx <= endIdx ? startIdx : 0;
107
+ chars.forEach((char, idx) => {
108
+ newChars.push(idx >= startIdx && idx <= endIdx ? maskWith : char);
109
+ });
110
+ newChars.push(afterChars);
111
+ return newChars.join('');
112
+ }
113
+
70
114
  exports.byteParse = byteParse;
71
115
  exports.byteStringify = byteStringify;
116
+ exports.maskData = maskData;