@wxhccc/es-util 1.4.0 → 1.5.2

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.3.1
2
+ * @wxhccc/es-util v1.5.2
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
  /**
@@ -400,6 +400,7 @@ function wrapPromise(promise, wrapOrOptions) {
400
400
  const unlock = () => stateLock(false);
401
401
  Object.defineProperties(corePromsie, {
402
402
  '__lockValue': { get: checkLock },
403
+ _checkLockKey: { value: (key) => lockCtx[key] },
403
404
  unlock: { value: unlock }
404
405
  });
405
406
  if (needLock && !ignoreLock) {
@@ -412,12 +413,118 @@ const wp = Object.defineProperty(wrapPromise, '_checkLockKey', { value: (key) =>
412
413
  const wpVuePlugin = {
413
414
  install(appOrVue, key = '$wp') {
414
415
  if (appOrVue.config && 'globalProperties' in appOrVue.config) {
415
- appOrVue.config.globalProperties[key] = wp;
416
+ appOrVue.config.globalProperties[key] = wrapPromise;
416
417
  }
417
418
  else {
418
- appOrVue.prototype[key] = wp;
419
+ appOrVue.prototype[key] = wrapPromise;
419
420
  }
420
421
  }
421
422
  };
422
423
 
423
- 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 options 额外的配置参数
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
+ const mapValue = maps[key];
499
+ if (!values || !mapValue) {
500
+ return acc;
501
+ }
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
+ /** 创建一个绑定了默认时间格式转换函数的formParamsSwitch函数 */
528
+ const formParamsSwitchCreator = (dateFormat) => (formData, maps, options) => formParamsSwitch(formData, maps, { dateFormat, ...options });
529
+
530
+ export { ChinaIdCardValid, array2tree, awaitWrapper, byteParse, byteStringify, checkoutBy, filterNullable, formParamsSwitch, formParamsSwitchCreator, 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.3.1
2
+ * @wxhccc/es-util v1.5.2
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
  /**
@@ -404,6 +404,7 @@ function wrapPromise(promise, wrapOrOptions) {
404
404
  const unlock = () => stateLock(false);
405
405
  Object.defineProperties(corePromsie, {
406
406
  '__lockValue': { get: checkLock },
407
+ _checkLockKey: { value: (key) => lockCtx[key] },
407
408
  unlock: { value: unlock }
408
409
  });
409
410
  if (needLock && !ignoreLock) {
@@ -416,24 +417,136 @@ const wp = Object.defineProperty(wrapPromise, '_checkLockKey', { value: (key) =>
416
417
  const wpVuePlugin = {
417
418
  install(appOrVue, key = '$wp') {
418
419
  if (appOrVue.config && 'globalProperties' in appOrVue.config) {
419
- appOrVue.config.globalProperties[key] = wp;
420
+ appOrVue.config.globalProperties[key] = wrapPromise;
420
421
  }
421
422
  else {
422
- appOrVue.prototype[key] = wp;
423
+ appOrVue.prototype[key] = wrapPromise;
423
424
  }
424
425
  }
425
426
  };
426
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 options 额外的配置参数
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
+ const mapValue = maps[key];
503
+ if (!values || !mapValue) {
504
+ return acc;
505
+ }
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
+ /** 创建一个绑定了默认时间格式转换函数的formParamsSwitch函数 */
532
+ const formParamsSwitchCreator = (dateFormat) => (formData, maps, options) => formParamsSwitch(formData, maps, { dateFormat, ...options });
533
+
427
534
  exports.ChinaIdCardValid = ChinaIdCardValid;
428
535
  exports.array2tree = array2tree;
429
536
  exports.awaitWrapper = awaitWrapper;
430
537
  exports.byteParse = byteParse;
431
538
  exports.byteStringify = byteStringify;
432
539
  exports.checkoutBy = checkoutBy;
540
+ exports.filterNullable = filterNullable;
541
+ exports.formParamsSwitch = formParamsSwitch;
542
+ exports.formParamsSwitchCreator = formParamsSwitchCreator;
433
543
  exports.formulaValidate = formulaValidate;
544
+ exports.isNullable = isNullable;
434
545
  exports.mapToObject = mapToObject;
435
546
  exports.objType = objType;
436
547
  exports.pickRenameKeys = pickRenameKeys;
548
+ exports.safeJsonParse = safeJsonParse;
549
+ exports.switchNullToUndefined = switchNullToUndefined;
437
550
  exports.tree2array = tree2array;
438
551
  exports.wp = wp;
439
552
  exports.wpVuePlugin = wpVuePlugin;
package/dist/index.min.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.3.1
2
+ * @wxhccc/es-util v1.5.2
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={};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: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},unlock:{value:M}}),j&&!m&&(x(!0),!d&&K.finally(M)),K}),"_checkLockKey",{value:e=>s[e]}),u={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=l,e.wpVuePlugin=u,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 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:f,lock:p,syncRefHandle:y,manualUnlock:d}="boolean"==typeof t?{wrap:t}:{...t};let b,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,a=o?{...e}:e;let s=a,l=!1;for(let e=0;e<t.length;e++){const n=t[e],c=m(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,{}),!B(s[n]))break;o&&(s[n]={...s[n]}),s=s[n]}}o&&l&&c.setState({[t[0]]:a[t[0]]})})(u,j,e):s[p]=e:(h&&(h[0][h[1]]=e),b&&b(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&&(b=p,e(y)&&(h=y)),g=j.length>0||!!h||!!b,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?a(e()):e():f?a(e):e;const K=()=>x(!1);return Object.defineProperties(k,{__lockValue:{get:A},_checkLockKey:{value:e=>s[e]},unlock:{value:K}}),g&&!O&&(x(!0),!d&&k.finally(K)),k}const u=Object.defineProperty(l,"_checkLockKey",{value:e=>s[e]}),f={install(e,t="$wp"){e.config&&"globalProperties"in e.config?e.config.globalProperties[t]=l:e.prototype[t]=l}};const p=(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)?p(i):i)})),n},{toString:y}=Object.prototype,d=e=>{if(null!==e)return Array.isArray(e)?e.map(d):("[object Object]"===y.call(e)&&Object.keys(e).forEach((t=>{e[t]=d(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:a,dateFormat:s}={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,a]=r;Object.assign(e,{[t]:s instanceof Function?s(o,i):o,[n]:s instanceof Function?s(a,i):a})}return e}),{}),u={...c,...l};return a?p(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: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={},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 a?a(f):a?{[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 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),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=a/t;return!(n>l)&&(p=e.units[r],y=f(n*s),!0)}));else{const e=Math.pow(l,u.expMax);p=u.units[r];y=f(a/e*s)}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=p,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.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=d,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=f,Object.defineProperty(e,"__esModule",{value:!0})}));
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.3.1
2
+ * @wxhccc/es-util v1.5.2
3
3
  * (c) 2021 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -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
@@ -23,10 +23,17 @@ export interface WpOptions {
23
23
  syncRefHandle?: SyncRefHandle;
24
24
  manualUnlock?: boolean;
25
25
  }
26
- declare type WpReturn<T> = PromiseWithLock<T | undefined | [null, T] | [Error, undefined]>;
26
+ declare type WpReturn<T> = PromiseWithLock<T | undefined>;
27
+ declare type WpArrReturn<T> = PromiseWithLock<[null, T] | [Error, undefined]>;
27
28
  declare type WpPromise<T> = Promise<T> | (() => Promise<T>);
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>;
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>;
30
37
  declare type WP = typeof wrapPromise & {
31
38
  _checkLockKey: (key: string) => boolean;
32
39
  };
package/dist/promise.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.3.1
2
+ * @wxhccc/es-util v1.5.2
3
3
  * (c) 2021 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -158,6 +158,7 @@ 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] },
161
162
  unlock: { value: unlock }
162
163
  });
163
164
  if (needLock && !ignoreLock) {
@@ -170,10 +171,10 @@ const wp = Object.defineProperty(wrapPromise, '_checkLockKey', { value: (key) =>
170
171
  const wpVuePlugin = {
171
172
  install(appOrVue, key = '$wp') {
172
173
  if (appOrVue.config && 'globalProperties' in appOrVue.config) {
173
- appOrVue.config.globalProperties[key] = wp;
174
+ appOrVue.config.globalProperties[key] = wrapPromise;
174
175
  }
175
176
  else {
176
- appOrVue.prototype[key] = wp;
177
+ appOrVue.prototype[key] = wrapPromise;
177
178
  }
178
179
  }
179
180
  };
package/dist/validate.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.3.1
2
+ * @wxhccc/es-util v1.5.2
3
3
  * (c) 2021 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.3.1
2
+ * @wxhccc/es-util v1.5.2
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.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
- }
1
+ {
2
+ "name": "@wxhccc/es-util",
3
+ "version": "1.5.2",
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';