@wxhccc/es-util 1.4.1 → 1.5.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,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.4.1
2
+ * @wxhccc/es-util v1.5.0
3
3
  * (c) 2021 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -249,9 +249,9 @@ function byteStringify(byteNum, options) {
249
249
  function byteParse(byteStr, options = {}) {
250
250
  }
251
251
 
252
- const { hasOwnProperty, toString } = Object.prototype;
252
+ const { hasOwnProperty, toString: toString$1 } = Object.prototype;
253
253
  const objType = (val) => {
254
- const typeKeys = toString.call(val).match(/^\[object (.*)\]$/);
254
+ const typeKeys = toString$1.call(val).match(/^\[object (.*)\]$/);
255
255
  return typeKeys ? typeKeys[1] : '';
256
256
  };
257
257
  /**
@@ -409,7 +409,7 @@ function wrapPromise(promise, wrapOrOptions) {
409
409
  }
410
410
  return corePromsie;
411
411
  }
412
- const wp = wrapPromise;
412
+ const wp = Object.defineProperty(wrapPromise, '_checkLockKey', { value: (key) => lockCtx[key] });
413
413
  const wpVuePlugin = {
414
414
  install(appOrVue, key = '$wp') {
415
415
  if (appOrVue.config && 'globalProperties' in appOrVue.config) {
@@ -421,4 +421,108 @@ const wpVuePlugin = {
421
421
  }
422
422
  };
423
423
 
424
- export { ChinaIdCardValid, array2tree, awaitWrapper, byteParse, byteStringify, checkoutBy, formulaValidate, mapToObject, objType, pickRenameKeys, tree2array, wp, wpVuePlugin };
424
+ function safeJsonParse(json = '', faileValue) {
425
+ try {
426
+ return JSON.parse(json);
427
+ }
428
+ catch (_e) {
429
+ return faileValue;
430
+ }
431
+ }
432
+ /**
433
+ * check value whether empty text
434
+ * 判断给定变量是否是字面量空值 */
435
+ const isNullable = (value) => value === '' || value === undefined || value === null;
436
+ /**
437
+ * 过滤对象中属性为空('' | undefined | null)的字段
438
+ * @param obj 给定对象
439
+ * @param deep 是否需要递归过滤
440
+ * @returns 过滤后的对象
441
+ */
442
+ const filterNullable = (obj, deep) => {
443
+ 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;
448
+ }
449
+ });
450
+ return result;
451
+ };
452
+ const { toString } = Object.prototype;
453
+ /**
454
+ * 将对象中属性值为null的转换为undefined
455
+ * @param data 对象数据
456
+ * @returns
457
+ */
458
+ const switchNullToUndefined = (data) => {
459
+ if (data === null) {
460
+ return undefined;
461
+ }
462
+ if (Array.isArray(data)) {
463
+ return data.map(switchNullToUndefined);
464
+ }
465
+ else if (toString.call(data) === '[object Object]') {
466
+ Object.keys(data).forEach((key) => {
467
+ data[key] = switchNullToUndefined(data[key]);
468
+ });
469
+ }
470
+ return data;
471
+ };
472
+ /**
473
+ * 将搜素条件里的数组字段转换为其他格式,通常用于搜索表单的字段转换
474
+ * @param formData 传入参数
475
+ * @param maps 转换的映射关系,eg:{ date: ['startTime', 'endTime'] }
476
+ * @param filterNullableValue 是否需要过滤掉空数据项
477
+ */
478
+ const formParamsSwitch = (formData, maps, options) => {
479
+ const dateKeys = Object.keys(maps);
480
+ const dateData = {};
481
+ const restData = {};
482
+ Object.keys(formData).forEach(key => {
483
+ if (dateKeys.includes(key)) {
484
+ dateData[key] = formData[key];
485
+ }
486
+ else {
487
+ restData[key] = formData[key];
488
+ }
489
+ });
490
+ const accessKeys = Object.keys(dateData);
491
+ // 如无需要转换的数据时,直接返回原对象
492
+ if (accessKeys.length === 0) {
493
+ return formData;
494
+ }
495
+ const { filterNullable: filterNullableValue, dateFormat } = { filterNullable: true, ...options };
496
+ const handleData = accessKeys.reduce((acc, key) => {
497
+ const values = dateData[key];
498
+ if (!values) {
499
+ return acc;
500
+ }
501
+ const mapValue = maps[key];
502
+ // 数组合并操作/取最后一位操作
503
+ if (mapValue === 'join' || mapValue === 'pop') {
504
+ if (Array.isArray(values) && values.length) {
505
+ acc[key] = mapValue === 'join' ? values.join(',') : values.slice(-1)[0];
506
+ }
507
+ }
508
+ else if (mapValue.length === 2 || mapValue.length === 3) {
509
+ if (!values || values.length !== 2) {
510
+ return acc;
511
+ }
512
+ const [startKey, endKey, format] = mapValue;
513
+ const [startValue, endValue] = values;
514
+ Object.assign(acc, {
515
+ [startKey]: dateFormat instanceof Function ? dateFormat(startValue, format) : startValue,
516
+ [endKey]: dateFormat instanceof Function ? dateFormat(endValue, format) : endValue
517
+ });
518
+ }
519
+ return acc;
520
+ }, {});
521
+ const result = {
522
+ ...restData,
523
+ ...handleData
524
+ };
525
+ return filterNullableValue ? filterNullable(result) : result;
526
+ };
527
+
528
+ export { ChinaIdCardValid, array2tree, awaitWrapper, byteParse, byteStringify, checkoutBy, filterNullable, formParamsSwitch, formulaValidate, isNullable, mapToObject, objType, pickRenameKeys, safeJsonParse, switchNullToUndefined, tree2array, wp, wpVuePlugin };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.4.1
2
+ * @wxhccc/es-util v1.5.0
3
3
  * (c) 2021 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -253,9 +253,9 @@ function byteStringify(byteNum, options) {
253
253
  function byteParse(byteStr, options = {}) {
254
254
  }
255
255
 
256
- const { hasOwnProperty, toString } = Object.prototype;
256
+ const { hasOwnProperty, toString: toString$1 } = Object.prototype;
257
257
  const objType = (val) => {
258
- const typeKeys = toString.call(val).match(/^\[object (.*)\]$/);
258
+ const typeKeys = toString$1.call(val).match(/^\[object (.*)\]$/);
259
259
  return typeKeys ? typeKeys[1] : '';
260
260
  };
261
261
  /**
@@ -413,7 +413,7 @@ function wrapPromise(promise, wrapOrOptions) {
413
413
  }
414
414
  return corePromsie;
415
415
  }
416
- const wp = wrapPromise;
416
+ const wp = Object.defineProperty(wrapPromise, '_checkLockKey', { value: (key) => lockCtx[key] });
417
417
  const wpVuePlugin = {
418
418
  install(appOrVue, key = '$wp') {
419
419
  if (appOrVue.config && 'globalProperties' in appOrVue.config) {
@@ -425,16 +425,125 @@ const wpVuePlugin = {
425
425
  }
426
426
  };
427
427
 
428
+ function safeJsonParse(json = '', faileValue) {
429
+ try {
430
+ return JSON.parse(json);
431
+ }
432
+ catch (_e) {
433
+ return faileValue;
434
+ }
435
+ }
436
+ /**
437
+ * check value whether empty text
438
+ * 判断给定变量是否是字面量空值 */
439
+ const isNullable = (value) => value === '' || value === undefined || value === null;
440
+ /**
441
+ * 过滤对象中属性为空('' | undefined | null)的字段
442
+ * @param obj 给定对象
443
+ * @param deep 是否需要递归过滤
444
+ * @returns 过滤后的对象
445
+ */
446
+ const filterNullable = (obj, deep) => {
447
+ const result = {};
448
+ Object.keys(obj).forEach(key => {
449
+ const value = obj[key];
450
+ if (value !== '' && value !== undefined && value !== null) {
451
+ result[key] = deep && Object.prototype.toString.call(value) === '[object Object]' ? filterNullable(value) : value;
452
+ }
453
+ });
454
+ return result;
455
+ };
456
+ const { toString } = Object.prototype;
457
+ /**
458
+ * 将对象中属性值为null的转换为undefined
459
+ * @param data 对象数据
460
+ * @returns
461
+ */
462
+ const switchNullToUndefined = (data) => {
463
+ if (data === null) {
464
+ return undefined;
465
+ }
466
+ if (Array.isArray(data)) {
467
+ return data.map(switchNullToUndefined);
468
+ }
469
+ else if (toString.call(data) === '[object Object]') {
470
+ Object.keys(data).forEach((key) => {
471
+ data[key] = switchNullToUndefined(data[key]);
472
+ });
473
+ }
474
+ return data;
475
+ };
476
+ /**
477
+ * 将搜素条件里的数组字段转换为其他格式,通常用于搜索表单的字段转换
478
+ * @param formData 传入参数
479
+ * @param maps 转换的映射关系,eg:{ date: ['startTime', 'endTime'] }
480
+ * @param filterNullableValue 是否需要过滤掉空数据项
481
+ */
482
+ const formParamsSwitch = (formData, maps, options) => {
483
+ const dateKeys = Object.keys(maps);
484
+ const dateData = {};
485
+ const restData = {};
486
+ Object.keys(formData).forEach(key => {
487
+ if (dateKeys.includes(key)) {
488
+ dateData[key] = formData[key];
489
+ }
490
+ else {
491
+ restData[key] = formData[key];
492
+ }
493
+ });
494
+ const accessKeys = Object.keys(dateData);
495
+ // 如无需要转换的数据时,直接返回原对象
496
+ if (accessKeys.length === 0) {
497
+ return formData;
498
+ }
499
+ const { filterNullable: filterNullableValue, dateFormat } = { filterNullable: true, ...options };
500
+ const handleData = accessKeys.reduce((acc, key) => {
501
+ const values = dateData[key];
502
+ if (!values) {
503
+ return acc;
504
+ }
505
+ const mapValue = maps[key];
506
+ // 数组合并操作/取最后一位操作
507
+ if (mapValue === 'join' || mapValue === 'pop') {
508
+ if (Array.isArray(values) && values.length) {
509
+ acc[key] = mapValue === 'join' ? values.join(',') : values.slice(-1)[0];
510
+ }
511
+ }
512
+ else if (mapValue.length === 2 || mapValue.length === 3) {
513
+ if (!values || values.length !== 2) {
514
+ return acc;
515
+ }
516
+ const [startKey, endKey, format] = mapValue;
517
+ const [startValue, endValue] = values;
518
+ Object.assign(acc, {
519
+ [startKey]: dateFormat instanceof Function ? dateFormat(startValue, format) : startValue,
520
+ [endKey]: dateFormat instanceof Function ? dateFormat(endValue, format) : endValue
521
+ });
522
+ }
523
+ return acc;
524
+ }, {});
525
+ const result = {
526
+ ...restData,
527
+ ...handleData
528
+ };
529
+ return filterNullableValue ? filterNullable(result) : result;
530
+ };
531
+
428
532
  exports.ChinaIdCardValid = ChinaIdCardValid;
429
533
  exports.array2tree = array2tree;
430
534
  exports.awaitWrapper = awaitWrapper;
431
535
  exports.byteParse = byteParse;
432
536
  exports.byteStringify = byteStringify;
433
537
  exports.checkoutBy = checkoutBy;
538
+ exports.filterNullable = filterNullable;
539
+ exports.formParamsSwitch = formParamsSwitch;
434
540
  exports.formulaValidate = formulaValidate;
541
+ exports.isNullable = isNullable;
435
542
  exports.mapToObject = mapToObject;
436
543
  exports.objType = objType;
437
544
  exports.pickRenameKeys = pickRenameKeys;
545
+ exports.safeJsonParse = safeJsonParse;
546
+ exports.switchNullToUndefined = switchNullToUndefined;
438
547
  exports.tree2array = tree2array;
439
548
  exports.wp = wp;
440
549
  exports.wpVuePlugin = wpVuePlugin;
package/dist/index.min.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.4.1
2
+ * @wxhccc/es-util v1.5.0
3
3
  * (c) 2021 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{hasOwnProperty:i,toString:c}=Object.prototype,o=e=>{const t=c.call(e).match(/^\[object (.*)\]$/);return t?t[1]:""};async function s(e){try{return[null,await e]}catch(e){return[e,void 0]}}const a={};const l=Object.defineProperty((function(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:a,l="react"===n?"state":"",u=l?c[l]:c,{wrap:f,lock:p,syncRefHandle:y,manualUnlock:b}="boolean"==typeof t?{wrap:t}:{...t};let d,h,j=[],g=!1,O=!1;const m=(e,t)=>!!e&&i.call(e,t),B=e=>"Object"===o(e),x=e=>{j.length?r?((e,t,r)=>{if("vue"===n&&c.$set&&!m(e,t[0]))return;const{$set:i=((e,t,n)=>{e[t]=n})}=c,o="react"===n,s=o?{...e}:e;let a=s,l=!1;for(let e=0;e<t.length;e++){const n=t[e],c=m(a,n);if(e===t.length-1){const e="boolean"==typeof a[n];l=!c||e,l&&i(a,n,r)}else{if(!c&&i(a,n,{}),!B(a[n]))break;o&&(a[n]={...a[n]}),a=a[n]}}o&&l&&c.setState({[t[0]]:s[t[0]]})})(u,j,e):a[p]=e:(h&&(h[0][h[1]]=e),d&&d(e))},A=()=>h?h[0][h[1]]:r||"string"!=typeof p?((e,t)=>{let n=!1;if(e&&B(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||!m(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)?h=p:"function"==typeof p&&(d=p,e(y)&&(h=y)),g=j.length>0||!!h||!!d,g&&(O=A())}let k;k="function"==typeof e?O?(()=>{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?s(e()):e():f?s(e):e;const K=()=>x(!1);return Object.defineProperties(k,{__lockValue:{get:A},unlock:{value:K}}),g&&!O&&(x(!0),!b&&k.finally(K)),k}),"_checkLockKey",{value:e=>a[e]}),u={install(e,t="$wp"){e.config&&"globalProperties"in e.config?e.config.globalProperties[t]=l:e.prototype[t]=l}};const f=(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)?f(i):i)})),n},{toString:p}=Object.prototype,y=e=>{if(null!==e)return Array.isArray(e)?e.map(y):("[object Object]"===p.call(e)&&Object.keys(e).forEach((t=>{e[t]=y(e[t])})),e)};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=s,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=f,e.formParamsSwitch=(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];if(!r)return e;const c=t[n];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?f(u):u},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.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.safeJsonParse=function(e="",t){try{return JSON.parse(e)}catch(e){return t}},e.switchNullToUndefined=y,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=l,e.wpVuePlugin=u,Object.defineProperty(e,"__esModule",{value:!0})}));
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.4.1
2
+ * @wxhccc/es-util v1.5.0
3
3
  * (c) 2021 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -0,0 +1,45 @@
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
+ /**
36
+ * 将搜素条件里的数组字段转换为其他格式,通常用于搜索表单的字段转换
37
+ * @param formData 传入参数
38
+ * @param maps 转换的映射关系,eg:{ date: ['startTime', 'endTime'] }
39
+ * @param filterNullableValue 是否需要过滤掉空数据项
40
+ */
41
+ export declare const formParamsSwitch: <T extends AnyObject, R extends AnyObject = AnyObject>(formData: T, maps: ParamsSwitchMaps, options?: {
42
+ filterNullable: boolean;
43
+ dateFormat: (date: unknown, format?: string | undefined) => string;
44
+ } | undefined) => R;
45
+ export {};
package/dist/promise.d.ts CHANGED
@@ -23,18 +23,14 @@ export interface WpOptions {
23
23
  syncRefHandle?: SyncRefHandle;
24
24
  manualUnlock?: boolean;
25
25
  }
26
- declare type WpReturn<T> = PromiseWithLock<T | undefined>;
27
- declare type WpArrReturn<T> = PromiseWithLock<[null, T] | [Error, undefined]>;
26
+ declare type WpReturn<T> = PromiseWithLock<T | undefined | [null, T] | [Error, undefined]>;
28
27
  declare type WpPromise<T> = Promise<T> | (() => Promise<T>);
29
- declare function wrapPromise<T>(this: any, promise: WpPromise<T>, wrap?: false): WpReturn<T>;
30
- declare function wrapPromise<T>(this: any, promise: WpPromise<T>, wrap: true): WpArrReturn<T>;
31
- declare function wrapPromise<T>(this: any, promise: WpPromise<T>, options?: WpOptions & {
32
- wrap?: false;
33
- }): WpReturn<T>;
34
- declare function wrapPromise<T>(this: any, promise: WpPromise<T>, options?: WpOptions & {
35
- wrap: true;
36
- }): WpArrReturn<T>;
37
- export declare const wp: typeof wrapPromise;
28
+ declare function wrapPromise<T>(this: any, promise: WpPromise<T>, wrap?: boolean): WpReturn<T>;
29
+ declare function wrapPromise<T>(this: any, promise: WpPromise<T>, options?: WpOptions): WpReturn<T>;
30
+ declare type WP = typeof wrapPromise & {
31
+ _checkLockKey: (key: string) => boolean;
32
+ };
33
+ export declare const wp: WP;
38
34
  export declare const wpVuePlugin: {
39
35
  install(appOrVue: any, key?: string): void;
40
36
  };
package/dist/promise.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.4.1
2
+ * @wxhccc/es-util v1.5.0
3
3
  * (c) 2021 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -158,7 +158,6 @@ function wrapPromise(promise, wrapOrOptions) {
158
158
  const unlock = () => stateLock(false);
159
159
  Object.defineProperties(corePromsie, {
160
160
  '__lockValue': { get: checkLock },
161
- _checkLockKey: { value: (key) => lockCtx[key] },
162
161
  unlock: { value: unlock }
163
162
  });
164
163
  if (needLock && !ignoreLock) {
@@ -167,14 +166,14 @@ function wrapPromise(promise, wrapOrOptions) {
167
166
  }
168
167
  return corePromsie;
169
168
  }
170
- const wp = wrapPromise;
169
+ const wp = Object.defineProperty(wrapPromise, '_checkLockKey', { value: (key) => lockCtx[key] });
171
170
  const wpVuePlugin = {
172
171
  install(appOrVue, key = '$wp') {
173
172
  if (appOrVue.config && 'globalProperties' in appOrVue.config) {
174
- appOrVue.config.globalProperties[key] = wrapPromise;
173
+ appOrVue.config.globalProperties[key] = wp;
175
174
  }
176
175
  else {
177
- appOrVue.prototype[key] = wrapPromise;
176
+ appOrVue.prototype[key] = wp;
178
177
  }
179
178
  }
180
179
  };
package/dist/validate.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.4.1
2
+ * @wxhccc/es-util v1.5.0
3
3
  * (c) 2021 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.4.1
2
+ * @wxhccc/es-util v1.5.0
3
3
  * (c) 2021 wxhccc
4
4
  * @license MIT
5
5
  */
package/package.json CHANGED
@@ -1,67 +1,67 @@
1
- {
2
- "name": "@wxhccc/es-util",
3
- "version": "1.4.1",
4
- "description": "A library that contains some useful methods",
5
- "main": "dist/index.js",
6
- "module": "dist/index.esm.js",
7
- "unpkg": "dist/index.min.js",
8
- "types": "types/index.d.ts",
9
- "scripts": {
10
- "start": "npm run dev",
11
- "test": "jest",
12
- "dev": "rollup -w -c --environment NODE_ENV:development",
13
- "build": "rollup -c"
14
- },
15
- "keywords": [
16
- "array-tree-switch",
17
- "array",
18
- "tree",
19
- "array2tree",
20
- "tree2array",
21
- "idCard",
22
- "validate",
23
- "mapToObject",
24
- "string-switch"
25
- ],
26
- "author": "wxhccc",
27
- "license": "MIT",
28
- "repository": {
29
- "type": "git",
30
- "url": "git+https://github.com/wxhccc/es-util.git"
31
- },
32
- "bugs": {
33
- "url": "https://github.com/wxhccc/es-util/issues"
34
- },
35
- "homepage": "https://github.com/wxhccc/es-util#readme",
36
- "devDependencies": {
37
- "@babel/core": "^7.3.3",
38
- "@babel/preset-env": "^7.3.1",
39
- "@babel/preset-react": "^7.13.13",
40
- "@rollup/plugin-babel": "^5.3.0",
41
- "@rollup/plugin-commonjs": "^18.0.0",
42
- "@rollup/plugin-node-resolve": "^11.2.1",
43
- "@types/jest": "^26.0.23",
44
- "@typescript-eslint/eslint-plugin": "^2.19.0",
45
- "@typescript-eslint/parser": "^2.19.0",
46
- "@vue/test-utils": "^2.0.0-rc.6",
47
- "babel-eslint": "^8.2.6",
48
- "enzyme": "^3.11.0",
49
- "enzyme-adapter-react-16": "^1.15.6",
50
- "eslint": "^4.19.1",
51
- "jest": "^26.6.3",
52
- "lodash": "^4.17.15",
53
- "react": "^17.0.2",
54
- "react-dom": "^17.0.2",
55
- "rollup": "^2.45.1",
56
- "rollup-plugin-terser": "^7.0.2",
57
- "rollup-plugin-typescript2": "^0.30.0",
58
- "tslib": "^1.10.0",
59
- "typescript": "^4.2.4",
60
- "vue": "^3.0.11"
61
- },
62
- "files": [
63
- "dist",
64
- "types"
65
- ],
66
- "dependencies": {}
67
- }
1
+ {
2
+ "name": "@wxhccc/es-util",
3
+ "version": "1.5.0",
4
+ "description": "A library that contains some useful methods",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.esm.js",
7
+ "unpkg": "dist/index.min.js",
8
+ "types": "types/index.d.ts",
9
+ "scripts": {
10
+ "start": "npm run dev",
11
+ "test": "jest",
12
+ "dev": "rollup -w -c --environment NODE_ENV:development",
13
+ "build": "rollup -c"
14
+ },
15
+ "keywords": [
16
+ "array-tree-switch",
17
+ "array",
18
+ "tree",
19
+ "array2tree",
20
+ "tree2array",
21
+ "idCard",
22
+ "validate",
23
+ "mapToObject",
24
+ "string-switch"
25
+ ],
26
+ "author": "wxhccc",
27
+ "license": "MIT",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/wxhccc/es-util.git"
31
+ },
32
+ "bugs": {
33
+ "url": "https://github.com/wxhccc/es-util/issues"
34
+ },
35
+ "homepage": "https://github.com/wxhccc/es-util#readme",
36
+ "devDependencies": {
37
+ "@babel/core": "^7.3.3",
38
+ "@babel/preset-env": "^7.3.1",
39
+ "@babel/preset-react": "^7.13.13",
40
+ "@rollup/plugin-babel": "^5.3.0",
41
+ "@rollup/plugin-commonjs": "^18.0.0",
42
+ "@rollup/plugin-node-resolve": "^11.2.1",
43
+ "@types/jest": "^26.0.23",
44
+ "@typescript-eslint/eslint-plugin": "^2.19.0",
45
+ "@typescript-eslint/parser": "^2.19.0",
46
+ "@vue/test-utils": "^2.0.0-rc.6",
47
+ "babel-eslint": "^8.2.6",
48
+ "enzyme": "^3.11.0",
49
+ "enzyme-adapter-react-16": "^1.15.6",
50
+ "eslint": "^4.19.1",
51
+ "jest": "^26.6.3",
52
+ "lodash": "^4.17.15",
53
+ "react": "^17.0.2",
54
+ "react-dom": "^17.0.2",
55
+ "rollup": "^2.45.1",
56
+ "rollup-plugin-terser": "^7.0.2",
57
+ "rollup-plugin-typescript2": "^0.30.0",
58
+ "tslib": "^1.10.0",
59
+ "typescript": "^4.2.4",
60
+ "vue": "^3.0.11"
61
+ },
62
+ "files": [
63
+ "dist",
64
+ "types"
65
+ ],
66
+ "dependencies": {}
67
+ }
package/types/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';
@@ -0,0 +1,45 @@
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
+ /**
36
+ * 将搜素条件里的数组字段转换为其他格式,通常用于搜索表单的字段转换
37
+ * @param formData 传入参数
38
+ * @param maps 转换的映射关系,eg:{ date: ['startTime', 'endTime'] }
39
+ * @param filterNullableValue 是否需要过滤掉空数据项
40
+ */
41
+ export declare const formParamsSwitch: <T extends AnyObject, R extends AnyObject = AnyObject>(formData: T, maps: ParamsSwitchMaps, options?: {
42
+ filterNullable: boolean;
43
+ dateFormat: (date: unknown, format?: string | undefined) => string;
44
+ } | undefined) => R;
45
+ export {};