@wxhccc/es-util 1.3.0 → 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.min.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.2.0
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,s=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 o={};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?this:o,c="react"===n?"state":"",u=c?r[c]:r,l=(e,t)=>!!e&&i.call(e,t),f=e=>"Object"===s(e),p=e=>{if(j.length)return((e,t,i)=>{if("vue"===n&&r.$set&&!l(e,t[0]))return;const{$set:c=((e,t,n)=>{e[t]=n})}=r,s="react"===n,a=s?{...e}:e;let o=a,u=!1;for(let e=0;e<t.length;e++){const n=t[e],r=l(o,n);if(e===t.length-1){const e="boolean"==typeof o[n];u=!r||e,u&&c(o,n,i)}else{if(!r&&c(o,n,{}),!f(o[n]))break;s&&(o[n]={...o[n]}),o=o[n]}}s&&u&&r.setState({[t[0]]:a[t[0]]})})(u,j,e);b&&(b[0][b[1]]=e),d&&d(e)},y=()=>((e,t)=>{if(b)return b[0][b[1]];let n=!1;if(e&&f(e)&&Array.isArray(t)){let r=e;for(let e=0;e<t.length;e++){const i=t[e];if("object"!=typeof r||!l(r,i))break;r=r[i],e===t.length-1&&(n="boolean"==typeof r&&r)}}return n})(u,j);let d,b,h,j=[];if("function"==typeof e){if(y())return;h=t?a(e()):e()}else h=t?a(e):e;return Object.defineProperties(h,{__lockValue:{get:y},lock:{value:(e,t)=>{const n=e=>Array.isArray(e)&&2===e.length;return"string"==typeof e?j=e.split("."):n(e)?b=e:"function"==typeof e&&(d=e,n(t)&&(b=t)),p(!0),h}}}),h.finally((()=>p(!1))),h}const l={install(e){e.config&&"globalProperties"in e.config?e.config.globalProperties.$wp=u:e.prototype.$wp=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,s=0;for(let t=0;t<17;t++)c=parseInt(e[t]),s=n[t],i+=c*s;return r[i%11].toString()===e[17]}return!0})()},e.array2tree=function(e,r={}){const{primaryKey:i,parentKey:c,childrenKey:s,createRoot:a,parentRefKey:o}=Object.assign({primaryKey:"id",parentKey:"pid",childrenKey:"children",createRoot:!1,parentRefKey:!1},r),u=o&&("string"==typeof o?o:"_parent");let l={},f=[];return Array.isArray(e)&&e.forEach((e=>{!t.call(l,e[i])&&(l[e[i]]=Object.assign({},e,n(s))),t.call(l,e[c])&&l[e[c]][s].push(Object.assign(l[e[i]],u?{[u]:l[e[c]]}:{})),!e[c]&&f.push(l[e[i]])})),"function"==typeof a?a(f):a?{[s]: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:s}=n;let a=parseFloat(e);if(!Number.isFinite(a))return;const o=a<0?-1:1;a=Math.abs(a);const{base:u,unitMap:l}=((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(l))l.some((e=>{const t=Math.pow(u,e.expMax),n=a/t;return!(n>u)&&(p=e.units[r],y=f(n*o),!0)}));else{const e=Math.pow(u,l.expMax);p=l.units[r];y=f(a/e*o)}return s?{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.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),s="string"==typeof n?e[n]:n(e,i);["string","number"].includes(typeof c)&&(r[c]=s)})),r},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.tree2array=function(e,t={}){const{primaryKey:r,parentKey:i,childrenKey:c,hasParentKey:s,returnObject:a}=Object.assign({hasParentKey:!0,primaryKey:"id",parentKey:"pid",childrenKey:"children",returnObject:!1},t);let o=a?{}:[];return Array.isArray(e)||"object"==typeof e?(function e(t,n,u=!1){let l=s?{}:{[i]:n};if(!u){const e=Object.assign(l,function(e,t){let n={};for(let r in e)r!==t&&(n[r]=e[r]);return n}(t,c));a?o[t[r]]=e:o.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),o):o},e.wp=u,e.wpVuePlugin=l,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})}));
@@ -0,0 +1,33 @@
1
+ declare type Obj = {
2
+ [key: string]: any;
3
+ };
4
+ /**
5
+ * translate object array to key-value map object
6
+ *
7
+ * @param {Object[]} objectArray
8
+ * @param {string} keyProp
9
+ * @param {string} valueProp
10
+ */
11
+ interface PropHandler {
12
+ (item: any, index: number): string;
13
+ }
14
+ export declare function mapToObject(objectArray: any[], keyProp?: string | PropHandler, valueProp?: string | PropHandler): Obj;
15
+ /**
16
+ * checkout values form object as an array
17
+ *
18
+ * @param {Object} object
19
+ * @param {string[] | Object} keys
20
+ * @param {string} valueProp
21
+ */
22
+ declare type MergeFn = <T>(...args: T[]) => T;
23
+ export declare function checkoutBy(object: Obj, keys?: string[] | Obj, mergeFn?: MergeFn): any[];
24
+ /**
25
+ * pick and rename object values
26
+ *
27
+ * @param {Object} object
28
+ * @param {Object} keysMap
29
+ */
30
+ export declare function pickRenameKeys(object: Obj, keysMap: {
31
+ [key: string]: string;
32
+ }): Obj | undefined;
33
+ export {};
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.2.0
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 {};
@@ -0,0 +1,37 @@
1
+ export declare const objType: (val: unknown) => string;
2
+ /**
3
+ * wrap promise and handle reject or err by return an array like [error, undefined]
4
+ * @param promise promise
5
+ * @returns Promise<[K, undefined] | [null, T]>
6
+ */
7
+ export declare function awaitWrapper<T, K = Error>(promise: Promise<T>): Promise<[null, T] | [K, undefined]>;
8
+ export declare type SyncRefHandle = [Record<string, boolean>, string];
9
+ export declare type LockSwitchHook = (val: boolean) => unknown;
10
+ export interface PromiseWithLock<T> extends Promise<T> {
11
+ readonly __lockValue: boolean;
12
+ unlock: () => void;
13
+ }
14
+ export declare type ContextType = 'react' | 'vue' | 'unknown';
15
+ /**
16
+ * wrap promise with lock, support reactive environment like react or vue
17
+ * @param promise promise
18
+ * @param wrap whether use awaitWrap to wrap result
19
+ */
20
+ export interface WpOptions {
21
+ wrap?: boolean;
22
+ lock?: string | LockSwitchHook | SyncRefHandle;
23
+ syncRefHandle?: SyncRefHandle;
24
+ manualUnlock?: boolean;
25
+ }
26
+ declare type WpReturn<T> = PromiseWithLock<T | undefined | [null, T] | [Error, undefined]>;
27
+ 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>;
30
+ declare type WP = typeof wrapPromise & {
31
+ _checkLockKey: (key: string) => boolean;
32
+ };
33
+ export declare const wp: WP;
34
+ export declare const wpVuePlugin: {
35
+ install(appOrVue: any, key?: string): void;
36
+ };
37
+ export {};
package/dist/promise.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.2.0
2
+ * @wxhccc/es-util v1.5.0
3
3
  * (c) 2021 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -37,20 +37,52 @@ function checkContext(context) {
37
37
  }
38
38
  return 'unknown';
39
39
  }
40
- /**
41
- * wrap promise with lock, support reactive environment like react or vue
42
- * @param promise promise
43
- * @param wrap whether use awaitWrap to wrap result
44
- */
40
+ const emptyPromise = () => {
41
+ const ep = Promise.resolve(undefined);
42
+ return Object.assign(ep, {
43
+ then(...args) {
44
+ const [onfulfilled] = args;
45
+ // if then has be called by Promise.all, let ite pass
46
+ if (args.length === 2 && typeof onfulfilled === 'function') {
47
+ return onfulfilled(undefined);
48
+ }
49
+ return ep;
50
+ },
51
+ catch: (onrejected) => ep,
52
+ finally: () => ep
53
+ });
54
+ };
45
55
  const lockCtx = {};
46
- function wp(promise, wrap) {
56
+ function wrapPromise(promise, wrapOrOptions) {
47
57
  const contextType = checkContext(this);
48
58
  const isReactiveIns = contextType !== 'unknown';
49
59
  const context = isReactiveIns ? this : lockCtx;
50
60
  const stateKey = contextType === 'react' ? 'state' : '';
51
61
  const contextState = stateKey ? context[stateKey] : context;
62
+ const { wrap, lock, syncRefHandle, manualUnlock } = typeof wrapOrOptions === 'boolean' ? { wrap: wrapOrOptions } : { ...wrapOrOptions };
63
+ let lockSwitchHook = undefined;
64
+ let lockRefHandle = undefined;
65
+ let lockKey = [];
66
+ let needLock = false;
67
+ let ignoreLock = false;
52
68
  const has = (val, key) => !!val && hasOwnProperty.call(val, key);
53
69
  const isObj = (obj) => objType(obj) === 'Object';
70
+ const getValue = (obj, path) => {
71
+ let result = false;
72
+ if (obj && isObj(obj) && Array.isArray(path) && path.length) {
73
+ let curObj = obj;
74
+ for (let i = 0; i < path.length; i++) {
75
+ const key = path[i];
76
+ if (typeof curObj !== 'object' || !has(curObj, key)) {
77
+ break;
78
+ }
79
+ curObj = curObj[key];
80
+ i === path.length - 1 &&
81
+ (result = (typeof curObj === 'boolean') ? curObj : false);
82
+ }
83
+ }
84
+ return result;
85
+ };
54
86
  const setValue = (obj, path, value) => {
55
87
  // if vue2 and path[0] not defined, do nothing
56
88
  if (contextType === 'vue' && context.$set && !has(obj, path[0]))
@@ -79,78 +111,69 @@ function wp(promise, wrap) {
79
111
  // trigger setState when run in react class component
80
112
  isStateRect && canSet && context.setState({ [path[0]]: originObj[path[0]] });
81
113
  };
82
- const getValue = (obj, path) => {
83
- // use refHandle if contextState not update sync
84
- if (lockRefHandle)
85
- return lockRefHandle[0][lockRefHandle[1]];
86
- let result = false;
87
- if (obj && isObj(obj) && Array.isArray(path)) {
88
- let curObj = obj;
89
- for (let i = 0; i < path.length; i++) {
90
- const key = path[i];
91
- if (typeof curObj !== 'object' || !has(curObj, key)) {
92
- break;
93
- }
94
- curObj = curObj[key];
95
- i === path.length - 1 &&
96
- (result = typeof curObj === 'boolean' ? curObj : false);
97
- }
98
- }
99
- return result;
100
- };
101
114
  const stateLock = (bool) => {
102
- if (lockKey.length)
103
- return setValue(contextState, lockKey, bool);
115
+ if (lockKey.length) {
116
+ // if not reactive instance, save lock key as string, no need to structure nested object
117
+ isReactiveIns ? setValue(contextState, lockKey, bool) : (lockCtx[lock] = bool);
118
+ return;
119
+ }
104
120
  if (lockRefHandle)
105
121
  lockRefHandle[0][lockRefHandle[1]] = bool;
106
122
  if (lockSwitchHook)
107
123
  lockSwitchHook(bool);
108
124
  };
109
- const checkLock = () => getValue(contextState, lockKey);
110
- let lockSwitchHook;
111
- let lockRefHandle;
112
- let lockKey = [];
125
+ const checkLock = () => {
126
+ // use refHandle if contextState not update sync
127
+ if (lockRefHandle)
128
+ return lockRefHandle[0][lockRefHandle[1]];
129
+ if (!isReactiveIns && typeof lock === 'string')
130
+ return contextState[lock];
131
+ return getValue(contextState, lockKey);
132
+ };
133
+ if (lock) {
134
+ const isRefHandle = (val) => Array.isArray(val) && val.length === 2;
135
+ if (typeof lock === 'string') {
136
+ lockKey = lock.split('.');
137
+ }
138
+ else if (isRefHandle(lock)) {
139
+ lockRefHandle = lock;
140
+ }
141
+ else if (typeof lock === 'function') {
142
+ lockSwitchHook = lock;
143
+ if (isRefHandle(syncRefHandle)) {
144
+ lockRefHandle = syncRefHandle;
145
+ }
146
+ }
147
+ needLock = lockKey.length > 0 || !!lockRefHandle || !!lockSwitchHook;
148
+ needLock && (ignoreLock = checkLock());
149
+ }
113
150
  let corePromsie;
151
+ // if promise is a function, here need to call it in promise.then to use locking check to prevent next call
114
152
  if (typeof promise === 'function') {
115
- if (checkLock())
116
- return;
117
- corePromsie = wrap ? awaitWrapper(promise()) : promise();
153
+ corePromsie = ignoreLock ? emptyPromise() : wrap ? awaitWrapper(promise()) : promise();
118
154
  }
119
155
  else {
120
156
  corePromsie = wrap ? awaitWrapper(promise) : promise;
121
157
  }
158
+ const unlock = () => stateLock(false);
122
159
  Object.defineProperties(corePromsie, {
123
- __lockValue: { get: checkLock },
124
- lock: {
125
- value: (keyOrHookOrHandle, syncRefHandle) => {
126
- const isRefHandle = (val) => Array.isArray(val) && val.length === 2;
127
- if (typeof keyOrHookOrHandle === 'string') {
128
- lockKey = keyOrHookOrHandle.split('.');
129
- }
130
- else if (isRefHandle(keyOrHookOrHandle)) {
131
- lockRefHandle = keyOrHookOrHandle;
132
- }
133
- else if (typeof keyOrHookOrHandle === 'function') {
134
- lockSwitchHook = keyOrHookOrHandle;
135
- if (isRefHandle(syncRefHandle)) {
136
- lockRefHandle = syncRefHandle;
137
- }
138
- }
139
- stateLock(true);
140
- return corePromsie;
141
- }
142
- }
160
+ '__lockValue': { get: checkLock },
161
+ unlock: { value: unlock }
143
162
  });
144
- corePromsie.finally(() => stateLock(false));
163
+ if (needLock && !ignoreLock) {
164
+ stateLock(true);
165
+ !manualUnlock && corePromsie.finally(unlock);
166
+ }
145
167
  return corePromsie;
146
168
  }
169
+ const wp = Object.defineProperty(wrapPromise, '_checkLockKey', { value: (key) => lockCtx[key] });
147
170
  const wpVuePlugin = {
148
- install(appOrVue) {
171
+ install(appOrVue, key = '$wp') {
149
172
  if (appOrVue.config && 'globalProperties' in appOrVue.config) {
150
- appOrVue.config.globalProperties.$wp = wp;
173
+ appOrVue.config.globalProperties[key] = wp;
151
174
  }
152
175
  else {
153
- appOrVue.prototype.$wp = wp;
176
+ appOrVue.prototype[key] = wp;
154
177
  }
155
178
  }
156
179
  };
@@ -0,0 +1,2 @@
1
+ export declare function ChinaIdCardValid(idNo: string): boolean;
2
+ export declare function formulaValidate(string: string, variables?: string[]): boolean;
package/dist/validate.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.2.0
2
+ * @wxhccc/es-util v1.5.0
3
3
  * (c) 2021 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -0,0 +1,12 @@
1
+ interface Options {
2
+ standard?: 'metric' | 'iec' | 'jedec';
3
+ unitLvl?: string;
4
+ precision?: number;
5
+ detail?: boolean;
6
+ }
7
+ export declare function byteStringify(byteNum: number | string, options?: Options): string | {
8
+ value: string | number;
9
+ unit: string;
10
+ } | undefined;
11
+ export declare function byteParse(byteStr: string, options?: {}): void;
12
+ export {};
@@ -0,0 +1 @@
1
+ export * from './byte-string';
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.2.0
2
+ * @wxhccc/es-util v1.5.0
3
3
  * (c) 2021 wxhccc
4
4
  * @license MIT
5
5
  */
package/package.json CHANGED
@@ -1,68 +1,67 @@
1
- {
2
- "name": "@wxhccc/es-util",
3
- "version": "1.3.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
- "@types/mocha": "^8.2.2",
45
- "@typescript-eslint/eslint-plugin": "^2.19.0",
46
- "@typescript-eslint/parser": "^2.19.0",
47
- "@vue/test-utils": "^2.0.0-rc.6",
48
- "babel-eslint": "^8.2.6",
49
- "enzyme": "^3.11.0",
50
- "enzyme-adapter-react-16": "^1.15.6",
51
- "eslint": "^4.19.1",
52
- "jest": "^26.6.3",
53
- "lodash": "^4.17.15",
54
- "react": "^17.0.2",
55
- "react-dom": "^17.0.2",
56
- "rollup": "^2.45.1",
57
- "rollup-plugin-terser": "^7.0.2",
58
- "rollup-plugin-typescript2": "^0.30.0",
59
- "tslib": "^1.10.0",
60
- "typescript": "^4.2.4",
61
- "vue": "^3.0.11"
62
- },
63
- "files": [
64
- "dist",
65
- "types"
66
- ],
67
- "dependencies": {}
68
- }
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 {};
@@ -7,17 +7,38 @@ export declare const objType: (val: unknown) => string;
7
7
  export declare function awaitWrapper<T, K = Error>(promise: Promise<T>): Promise<[null, T] | [K, undefined]>;
8
8
  export declare type SyncRefHandle = [Record<string, boolean>, string];
9
9
  export declare type LockSwitchHook = (val: boolean) => unknown;
10
- export interface LockMethod<T> {
11
- (key: string): Promise<T>;
12
- (syncRefHandle: SyncRefHandle): Promise<T>;
13
- (switchHook: LockSwitchHook, syncRefHandle?: [Record<string, boolean>, string]): Promise<T>;
14
- }
15
10
  export interface PromiseWithLock<T> extends Promise<T> {
16
11
  readonly __lockValue: boolean;
17
- lock: LockMethod<T>;
12
+ unlock: () => void;
18
13
  }
19
14
  export declare type ContextType = 'react' | 'vue' | 'unknown';
20
- export declare function wp<T>(this: any, promise: Promise<T> | (() => Promise<T>), wrap?: boolean): PromiseWithLock<T | [null, T] | [Error, undefined]> | undefined;
15
+ /**
16
+ * wrap promise with lock, support reactive environment like react or vue
17
+ * @param promise promise
18
+ * @param wrap whether use awaitWrap to wrap result
19
+ */
20
+ export interface WpOptions {
21
+ wrap?: boolean;
22
+ lock?: string | LockSwitchHook | SyncRefHandle;
23
+ syncRefHandle?: SyncRefHandle;
24
+ manualUnlock?: boolean;
25
+ }
26
+ declare type WpReturn<T> = PromiseWithLock<T | undefined>;
27
+ declare type WpArrReturn<T> = PromiseWithLock<[null, T] | [Error, undefined]>;
28
+ 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
+ declare type WP = typeof wrapPromise & {
38
+ _checkLockKey: (key: string) => boolean;
39
+ };
40
+ export declare const wp: WP;
21
41
  export declare const wpVuePlugin: {
22
- install(appOrVue: any): void;
42
+ install(appOrVue: any, key?: string): void;
23
43
  };
44
+ export {};