@wxhccc/es-util 1.6.0 → 1.7.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/README.md CHANGED
@@ -439,5 +439,27 @@ wrap promise or a function return promise with lock method to control UI or forb
439
439
 
440
440
  an plugin object for vue
441
441
 
442
+
443
+ ## event-target-emitter module
444
+
445
+ > v1.7.0 add
446
+
447
+ ### `eventTargetEmitter(options)`
448
+
449
+ return an emitter instance with `on`, `off` and some other methods to handle with EventTarget
450
+
451
+ **parameters:**
452
+ - **options** {ConfigOptions}
453
+ - **name** {string} the name of current emitter. can used to limit message received from
454
+ - **customHanlderCreator** {(watchers) => Function} custome handler creator, you can handle message distribute logic as you want.
455
+
456
+ ## event-target-emitter module
457
+
458
+ > v1.7.0 add
459
+
460
+ ### `pageCommunicate(options)`
461
+
462
+ return an instance which can used to communicate between same-origin pages, powered by `eventTargetEmitter`
463
+
442
464
  ## License
443
465
  MIT
@@ -0,0 +1,45 @@
1
+ import { AnyFunction } from "./types";
2
+ export interface EventPayload<T = any> {
3
+ /** method name to be listenered */
4
+ method: string;
5
+ /** carry data */
6
+ data?: T;
7
+ /** where the event emit from */
8
+ originEmitterName?: string;
9
+ /** which emitter can recived the event */
10
+ targetEmitterName?: string;
11
+ }
12
+ export declare type WatchersMap = Map<string | symbol, Set<AnyFunction>>;
13
+ export interface ConfigOptions {
14
+ /** the name of current emitter */
15
+ name?: string;
16
+ /** creator to return custom event handler */
17
+ customHanlderCreator?: (watchers: WatchersMap) => <T = any>(payload: EventPayload<T>) => void;
18
+ }
19
+ export interface BindOptions {
20
+ /** 限制消息来源 */
21
+ limitFrom?: string;
22
+ /** 事件所在命名空间 */
23
+ namespace?: string;
24
+ }
25
+ export declare const NOMETHOD: symbol;
26
+ /**
27
+ * 创建emitter形式的实例,可以通过实例封装事件对象,比如websocket,得到一个更便捷的方法,具体可参考page-communicate.js文件内容
28
+ * @param options 配置项
29
+ * @returns
30
+ */
31
+ export declare function eventTargetEmitter(options?: ConfigOptions): {
32
+ name: string | undefined;
33
+ rootEventListener: <T = any>(payload: EventPayload<T>) => void;
34
+ on: <T_1>(method: string | symbol, listener: (data: T_1) => any, options?: BindOptions | undefined) => void;
35
+ off: (method: string | symbol, callback?: AnyFunction<any> | undefined, options?: BindOptions | undefined) => void;
36
+ emit: (methodOrPayload: string | EventPayload<any>, data?: any, target?: string | undefined) => void;
37
+ createPayload: (methodOrPayload: string | EventPayload, data?: any, target?: string | undefined) => EventPayload<any>;
38
+ removeAllListeners: () => void;
39
+ getMethodNames: {
40
+ (all?: false | undefined): string[];
41
+ (all: true): string[][];
42
+ };
43
+ getListeners: (method: string | symbol, options?: BindOptions | undefined) => AnyFunction<any>[];
44
+ };
45
+ export default eventTargetEmitter;
@@ -0,0 +1,126 @@
1
+ /*!
2
+ * @wxhccc/es-util v1.7.0
3
+ * (c) 2022 wxhccc
4
+ * @license MIT
5
+ */
6
+ 'use strict';
7
+
8
+ Object.defineProperty(exports, '__esModule', { value: true });
9
+
10
+ const isStr = (val) => typeof val === 'string';
11
+ const NOMETHOD = Symbol('NOMETHOD');
12
+ /**
13
+ * 创建emitter形式的实例,可以通过实例封装事件对象,比如websocket,得到一个更便捷的方法,具体可参考page-communicate.js文件内容
14
+ * @param options 配置项
15
+ * @returns
16
+ */
17
+ function eventTargetEmitter(options) {
18
+ const watchers = new Map([[NOMETHOD, new Set()]]);
19
+ const { name: currentName, customHanlderCreator } = options || {};
20
+ const customHanlder = customHanlderCreator instanceof Function ? customHanlderCreator(watchers) : null;
21
+ const splitRegExp = /\|-[a-z]+-\|/;
22
+ const listenerSafeRun = (listener, ...args) => {
23
+ try {
24
+ listener(...args);
25
+ }
26
+ catch (e) {
27
+ console.error(e);
28
+ }
29
+ };
30
+ const defaultHanlder = (payload) => {
31
+ const { method, data, originEmitterName: from, targetEmitterName: to } = payload || [];
32
+ if (method && typeof method === 'string') {
33
+ const matchListeners = [];
34
+ watchers.forEach((value, key) => {
35
+ if (typeof key === 'string' && key.startsWith(method)) {
36
+ const [, eFrom,] = key.split(splitRegExp);
37
+ if (!eFrom || !from || eFrom === from) {
38
+ matchListeners.push(...value);
39
+ }
40
+ }
41
+ });
42
+ if (matchListeners.length && (!currentName || !to || currentName === to)) {
43
+ matchListeners.forEach(listener => listenerSafeRun(listener, data));
44
+ }
45
+ }
46
+ const noMethodListeners = watchers.get(NOMETHOD);
47
+ if (noMethodListeners) {
48
+ noMethodListeners.forEach(listener => listenerSafeRun(listener, data, payload));
49
+ }
50
+ };
51
+ const rootEventListener = customHanlder instanceof Function ? customHanlder : defaultHanlder;
52
+ const getFullMethodName = (method, options) => {
53
+ const { limitFrom = '', namespace = '' } = options || {};
54
+ return (limitFrom || namespace) && typeof method === 'string' ? `${method}|-from-|${limitFrom}|-ns-|${namespace}` : method;
55
+ };
56
+ const on = (method, listener, options) => {
57
+ if (typeof method === 'symbol' && method !== NOMETHOD) {
58
+ return;
59
+ }
60
+ const trueMethod = getFullMethodName(method, options);
61
+ if (!watchers.has(trueMethod)) {
62
+ watchers.set(trueMethod, new Set());
63
+ }
64
+ const listeners = watchers.get(trueMethod);
65
+ listeners?.add(listener);
66
+ };
67
+ const off = (method, callback, options) => {
68
+ if (typeof method === 'symbol' && method !== NOMETHOD) {
69
+ return;
70
+ }
71
+ const { limitFrom, namespace } = options || {};
72
+ if (namespace && !method) {
73
+ watchers.forEach((_value, key) => {
74
+ if (typeof key === 'string' && key.endsWith(namespace)) {
75
+ watchers.delete(key);
76
+ }
77
+ });
78
+ return;
79
+ }
80
+ const trueMethod = getFullMethodName(method, options);
81
+ if (!callback) {
82
+ watchers.delete(trueMethod);
83
+ return;
84
+ }
85
+ watchers.get(trueMethod)?.delete(callback);
86
+ };
87
+ const removeAllListeners = () => {
88
+ watchers.clear();
89
+ };
90
+ const createPayload = (methodOrPayload, data, target) => {
91
+ return isStr(methodOrPayload) ? {
92
+ method: methodOrPayload,
93
+ data,
94
+ ...(target && isStr(target) ? { targetEmitterName: target } : {}),
95
+ ...(currentName && isStr(currentName) ? { originEmitterName: currentName } : {})
96
+ } : methodOrPayload;
97
+ };
98
+ const emit = (...args) => {
99
+ const payload = createPayload(...args);
100
+ rootEventListener(payload);
101
+ };
102
+ /** 获取当前所有监听方法的方法名,默认仅返回函数名,设置all为true可以返回具体来源限制和命名空间字段 */
103
+ const getMethodNames = (all) => {
104
+ if (!all) {
105
+ const result = [];
106
+ watchers.forEach((_v, key) => isStr(key) && result.push(key.split(splitRegExp)));
107
+ return result;
108
+ }
109
+ const result = [];
110
+ watchers.forEach((_v, key) => isStr(key) && result.push(key));
111
+ return result;
112
+ };
113
+ const getListeners = (method, options) => {
114
+ if (typeof method === 'symbol') {
115
+ return method === NOMETHOD ? Array.from(watchers.get(NOMETHOD) || []) : [];
116
+ }
117
+ const trueMethod = getFullMethodName(method, options);
118
+ const listeners = watchers.get(trueMethod);
119
+ return listeners ? Array.from(listeners) : [];
120
+ };
121
+ return { name: currentName, rootEventListener, on, off, emit, createPayload, removeAllListeners, getMethodNames, getListeners };
122
+ }
123
+
124
+ exports.NOMETHOD = NOMETHOD;
125
+ exports.default = eventTargetEmitter;
126
+ exports.eventTargetEmitter = eventTargetEmitter;
package/dist/index.d.ts CHANGED
@@ -4,3 +4,5 @@ export * from './object-array';
4
4
  export * from './value-string-switch';
5
5
  export * from './promise';
6
6
  export * from './optional';
7
+ export * from './event-target-emitter';
8
+ export * from './page-communicate';
package/dist/index.esm.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.6.0
2
+ * @wxhccc/es-util v1.7.0
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -18,13 +18,14 @@ function createNode(children, value = []) {
18
18
  * @param {boolean | string} parentRefKey parent reference key of node
19
19
  */
20
20
  function array2tree(array, options = {}) {
21
- const { primaryKey: id, parentKey: pid, childrenKey: children, createRoot, parentRefKey } = Object.assign({
21
+ const { primaryKey: id, parentKey: pid, childrenKey: children, createRoot, parentRefKey } = {
22
22
  primaryKey: 'id',
23
23
  parentKey: 'pid',
24
24
  childrenKey: 'children',
25
25
  createRoot: false,
26
- parentRefKey: false
27
- }, options);
26
+ parentRefKey: false,
27
+ ...options
28
+ };
28
29
  const pRefKey = parentRefKey && (typeof parentRefKey === 'string' ? parentRefKey : '_parent');
29
30
  let nodeMap = {};
30
31
  let treeNodes = [];
@@ -33,7 +34,7 @@ function array2tree(array, options = {}) {
33
34
  hasOwnProperty$1.call(nodeMap, item[pid]) && nodeMap[item[pid]][children].push(Object.assign(nodeMap[item[id]], pRefKey ? { [pRefKey]: nodeMap[item[pid]] } : {}));
34
35
  !item[pid] && treeNodes.push(nodeMap[item[id]]);
35
36
  });
36
- if (typeof createRoot === 'function') {
37
+ if (createRoot instanceof Function) {
37
38
  return createRoot(treeNodes);
38
39
  }
39
40
  else if (createRoot) {
@@ -150,7 +151,7 @@ function formulaValidate(string, variables) {
150
151
  }
151
152
 
152
153
  function mapToObject(objectArray, keyProp = 'key', valueProp = 'value') {
153
- let result = {};
154
+ const result = {};
154
155
  Array.isArray(objectArray) && keyProp && valueProp
155
156
  && [keyProp, valueProp].every(val => ['string', 'function'].includes(typeof val))
156
157
  && objectArray.forEach((item, index) => {
@@ -160,15 +161,24 @@ function mapToObject(objectArray, keyProp = 'key', valueProp = 'value') {
160
161
  });
161
162
  return result;
162
163
  }
164
+ const isObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]';
165
+ /**
166
+ * checkout values form object as an array
167
+ *
168
+ * @param {Object} object
169
+ * @param {string[] | Object} keys
170
+ * @param {string} valueProp
171
+ */
163
172
  function checkoutBy(object, keys, mergeFn) {
164
- if (!(object instanceof Object))
173
+ if (!isObject(object)) {
165
174
  return [];
175
+ }
166
176
  if (Array.isArray(keys)) {
167
- return keys.map(item => (object[item]));
177
+ return keys.map(item => object[item]);
168
178
  }
169
- else if (keys && keys instanceof Object) {
170
- return Object.keys(keys).map(item => (object[item] instanceof Object && keys[item] instanceof Object)
171
- ? (mergeFn ? mergeFn({}, object[item], keys[item]) : Object.assign({}, object[item], keys[item]))
179
+ else if (keys && isObject(keys)) {
180
+ return Object.keys(keys).map(item => (isObject(object[item]) && isObject(keys[item]))
181
+ ? (mergeFn ? mergeFn({}, (object)[item], (keys)[item]) : Object.assign({}, object[item], keys[item]))
172
182
  : (keys[item] || object[item]));
173
183
  }
174
184
  return Object.values(object);
@@ -180,8 +190,9 @@ function checkoutBy(object, keys, mergeFn) {
180
190
  * @param {Object} keysMap
181
191
  */
182
192
  function pickRenameKeys(object, keysMap) {
183
- if (!object || !(object instanceof Object) || !keysMap || !(keysMap instanceof Object))
193
+ if (!object || !isObject(object) || !keysMap || !isObject(keysMap)) {
184
194
  return;
195
+ }
185
196
  let result = {};
186
197
  for (let i in object) {
187
198
  (i in keysMap) && (result[keysMap[i]] = object[i]);
@@ -571,4 +582,165 @@ const formParamsSwitch = (formData, maps, options) => {
571
582
  /** 创建一个绑定了默认时间格式转换函数的formParamsSwitch函数 */
572
583
  const formParamsSwitchCreator = (dateFormat) => (formData, maps, options) => formParamsSwitch(formData, maps, { dateFormat, ...options });
573
584
 
574
- export { ChinaIdCardValid, array2tree, awaitWrapper, byteParse, byteStringify, checkoutBy, filterNullable, formParamsSwitch, formParamsSwitchCreator, formulaValidate, isNullable, mapToObject, maskData, objType, pickRenameKeys, safeJsonParse, switchNullToUndefined, tree2array, wp, wpVuePlugin };
585
+ const isStr = (val) => typeof val === 'string';
586
+ const NOMETHOD = Symbol('NOMETHOD');
587
+ /**
588
+ * 创建emitter形式的实例,可以通过实例封装事件对象,比如websocket,得到一个更便捷的方法,具体可参考page-communicate.js文件内容
589
+ * @param options 配置项
590
+ * @returns
591
+ */
592
+ function eventTargetEmitter(options) {
593
+ const watchers = new Map([[NOMETHOD, new Set()]]);
594
+ const { name: currentName, customHanlderCreator } = options || {};
595
+ const customHanlder = customHanlderCreator instanceof Function ? customHanlderCreator(watchers) : null;
596
+ const splitRegExp = /\|-[a-z]+-\|/;
597
+ const listenerSafeRun = (listener, ...args) => {
598
+ try {
599
+ listener(...args);
600
+ }
601
+ catch (e) {
602
+ console.error(e);
603
+ }
604
+ };
605
+ const defaultHanlder = (payload) => {
606
+ const { method, data, originEmitterName: from, targetEmitterName: to } = payload || [];
607
+ if (method && typeof method === 'string') {
608
+ const matchListeners = [];
609
+ watchers.forEach((value, key) => {
610
+ if (typeof key === 'string' && key.startsWith(method)) {
611
+ const [, eFrom,] = key.split(splitRegExp);
612
+ if (!eFrom || !from || eFrom === from) {
613
+ matchListeners.push(...value);
614
+ }
615
+ }
616
+ });
617
+ if (matchListeners.length && (!currentName || !to || currentName === to)) {
618
+ matchListeners.forEach(listener => listenerSafeRun(listener, data));
619
+ }
620
+ }
621
+ const noMethodListeners = watchers.get(NOMETHOD);
622
+ if (noMethodListeners) {
623
+ noMethodListeners.forEach(listener => listenerSafeRun(listener, data, payload));
624
+ }
625
+ };
626
+ const rootEventListener = customHanlder instanceof Function ? customHanlder : defaultHanlder;
627
+ const getFullMethodName = (method, options) => {
628
+ const { limitFrom = '', namespace = '' } = options || {};
629
+ return (limitFrom || namespace) && typeof method === 'string' ? `${method}|-from-|${limitFrom}|-ns-|${namespace}` : method;
630
+ };
631
+ const on = (method, listener, options) => {
632
+ if (typeof method === 'symbol' && method !== NOMETHOD) {
633
+ return;
634
+ }
635
+ const trueMethod = getFullMethodName(method, options);
636
+ if (!watchers.has(trueMethod)) {
637
+ watchers.set(trueMethod, new Set());
638
+ }
639
+ const listeners = watchers.get(trueMethod);
640
+ listeners?.add(listener);
641
+ };
642
+ const off = (method, callback, options) => {
643
+ if (typeof method === 'symbol' && method !== NOMETHOD) {
644
+ return;
645
+ }
646
+ const { limitFrom, namespace } = options || {};
647
+ if (namespace && !method) {
648
+ watchers.forEach((_value, key) => {
649
+ if (typeof key === 'string' && key.endsWith(namespace)) {
650
+ watchers.delete(key);
651
+ }
652
+ });
653
+ return;
654
+ }
655
+ const trueMethod = getFullMethodName(method, options);
656
+ if (!callback) {
657
+ watchers.delete(trueMethod);
658
+ return;
659
+ }
660
+ watchers.get(trueMethod)?.delete(callback);
661
+ };
662
+ const removeAllListeners = () => {
663
+ watchers.clear();
664
+ };
665
+ const createPayload = (methodOrPayload, data, target) => {
666
+ return isStr(methodOrPayload) ? {
667
+ method: methodOrPayload,
668
+ data,
669
+ ...(target && isStr(target) ? { targetEmitterName: target } : {}),
670
+ ...(currentName && isStr(currentName) ? { originEmitterName: currentName } : {})
671
+ } : methodOrPayload;
672
+ };
673
+ const emit = (...args) => {
674
+ const payload = createPayload(...args);
675
+ rootEventListener(payload);
676
+ };
677
+ /** 获取当前所有监听方法的方法名,默认仅返回函数名,设置all为true可以返回具体来源限制和命名空间字段 */
678
+ const getMethodNames = (all) => {
679
+ if (!all) {
680
+ const result = [];
681
+ watchers.forEach((_v, key) => isStr(key) && result.push(key.split(splitRegExp)));
682
+ return result;
683
+ }
684
+ const result = [];
685
+ watchers.forEach((_v, key) => isStr(key) && result.push(key));
686
+ return result;
687
+ };
688
+ const getListeners = (method, options) => {
689
+ if (typeof method === 'symbol') {
690
+ return method === NOMETHOD ? Array.from(watchers.get(NOMETHOD) || []) : [];
691
+ }
692
+ const trueMethod = getFullMethodName(method, options);
693
+ const listeners = watchers.get(trueMethod);
694
+ return listeners ? Array.from(listeners) : [];
695
+ };
696
+ return { name: currentName, rootEventListener, on, off, emit, createPayload, removeAllListeners, getMethodNames, getListeners };
697
+ }
698
+
699
+ /**
700
+ * 创建同源页面之间通信的封装实例,默认使用BroadcastChannel实现,在不支持的浏览器环境中会使用localstorage实现
701
+ * @param options 配置对象
702
+ * @returns
703
+ */
704
+ function pageCommunicate(options) {
705
+ const { messageHanlder, currentPage } = options || {};
706
+ const { emit, on, off, createPayload, removeAllListeners } = eventTargetEmitter({ name: currentPage, customHanlderCreator: messageHanlder });
707
+ const onMessage = (event) => emit(event.data);
708
+ let bc;
709
+ const ls = window.localStorage;
710
+ const channelName = 'PAGE_COMMUNICATE_CHANNEL';
711
+ if (typeof BroadcastChannel !== undefined) {
712
+ bc = new BroadcastChannel(channelName);
713
+ bc.addEventListener('message', onMessage);
714
+ }
715
+ else {
716
+ const onStorageMessage = () => {
717
+ const payload = safeJsonParse(ls.getItem(channelName) || '');
718
+ if (payload) {
719
+ emit(payload);
720
+ }
721
+ };
722
+ window.addEventListener('storage', onStorageMessage);
723
+ }
724
+ const send = (...args) => {
725
+ const payload = createPayload(...args);
726
+ if (bc) {
727
+ bc.postMessage(payload);
728
+ }
729
+ else {
730
+ const payloadWitchTs = JSON.stringify({ ...payload, ts: +new Date() });
731
+ ls.setItem(channelName, payloadWitchTs);
732
+ }
733
+ };
734
+ const destory = () => {
735
+ removeAllListeners();
736
+ if (bc) {
737
+ bc.close();
738
+ }
739
+ else {
740
+ ls.removeItem(channelName);
741
+ }
742
+ };
743
+ return { on, off, send, destory };
744
+ }
745
+
746
+ export { ChinaIdCardValid, NOMETHOD, array2tree, awaitWrapper, byteParse, byteStringify, checkoutBy, eventTargetEmitter, filterNullable, formParamsSwitch, formParamsSwitchCreator, formulaValidate, isNullable, mapToObject, maskData, objType, pageCommunicate, pickRenameKeys, safeJsonParse, switchNullToUndefined, tree2array, wp, wpVuePlugin };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.6.0
2
+ * @wxhccc/es-util v1.7.0
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -22,13 +22,14 @@ function createNode(children, value = []) {
22
22
  * @param {boolean | string} parentRefKey parent reference key of node
23
23
  */
24
24
  function array2tree(array, options = {}) {
25
- const { primaryKey: id, parentKey: pid, childrenKey: children, createRoot, parentRefKey } = Object.assign({
25
+ const { primaryKey: id, parentKey: pid, childrenKey: children, createRoot, parentRefKey } = {
26
26
  primaryKey: 'id',
27
27
  parentKey: 'pid',
28
28
  childrenKey: 'children',
29
29
  createRoot: false,
30
- parentRefKey: false
31
- }, options);
30
+ parentRefKey: false,
31
+ ...options
32
+ };
32
33
  const pRefKey = parentRefKey && (typeof parentRefKey === 'string' ? parentRefKey : '_parent');
33
34
  let nodeMap = {};
34
35
  let treeNodes = [];
@@ -37,7 +38,7 @@ function array2tree(array, options = {}) {
37
38
  hasOwnProperty$1.call(nodeMap, item[pid]) && nodeMap[item[pid]][children].push(Object.assign(nodeMap[item[id]], pRefKey ? { [pRefKey]: nodeMap[item[pid]] } : {}));
38
39
  !item[pid] && treeNodes.push(nodeMap[item[id]]);
39
40
  });
40
- if (typeof createRoot === 'function') {
41
+ if (createRoot instanceof Function) {
41
42
  return createRoot(treeNodes);
42
43
  }
43
44
  else if (createRoot) {
@@ -154,7 +155,7 @@ function formulaValidate(string, variables) {
154
155
  }
155
156
 
156
157
  function mapToObject(objectArray, keyProp = 'key', valueProp = 'value') {
157
- let result = {};
158
+ const result = {};
158
159
  Array.isArray(objectArray) && keyProp && valueProp
159
160
  && [keyProp, valueProp].every(val => ['string', 'function'].includes(typeof val))
160
161
  && objectArray.forEach((item, index) => {
@@ -164,15 +165,24 @@ function mapToObject(objectArray, keyProp = 'key', valueProp = 'value') {
164
165
  });
165
166
  return result;
166
167
  }
168
+ const isObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]';
169
+ /**
170
+ * checkout values form object as an array
171
+ *
172
+ * @param {Object} object
173
+ * @param {string[] | Object} keys
174
+ * @param {string} valueProp
175
+ */
167
176
  function checkoutBy(object, keys, mergeFn) {
168
- if (!(object instanceof Object))
177
+ if (!isObject(object)) {
169
178
  return [];
179
+ }
170
180
  if (Array.isArray(keys)) {
171
- return keys.map(item => (object[item]));
181
+ return keys.map(item => object[item]);
172
182
  }
173
- else if (keys && keys instanceof Object) {
174
- return Object.keys(keys).map(item => (object[item] instanceof Object && keys[item] instanceof Object)
175
- ? (mergeFn ? mergeFn({}, object[item], keys[item]) : Object.assign({}, object[item], keys[item]))
183
+ else if (keys && isObject(keys)) {
184
+ return Object.keys(keys).map(item => (isObject(object[item]) && isObject(keys[item]))
185
+ ? (mergeFn ? mergeFn({}, (object)[item], (keys)[item]) : Object.assign({}, object[item], keys[item]))
176
186
  : (keys[item] || object[item]));
177
187
  }
178
188
  return Object.values(object);
@@ -184,8 +194,9 @@ function checkoutBy(object, keys, mergeFn) {
184
194
  * @param {Object} keysMap
185
195
  */
186
196
  function pickRenameKeys(object, keysMap) {
187
- if (!object || !(object instanceof Object) || !keysMap || !(keysMap instanceof Object))
197
+ if (!object || !isObject(object) || !keysMap || !isObject(keysMap)) {
188
198
  return;
199
+ }
189
200
  let result = {};
190
201
  for (let i in object) {
191
202
  (i in keysMap) && (result[keysMap[i]] = object[i]);
@@ -575,12 +586,175 @@ const formParamsSwitch = (formData, maps, options) => {
575
586
  /** 创建一个绑定了默认时间格式转换函数的formParamsSwitch函数 */
576
587
  const formParamsSwitchCreator = (dateFormat) => (formData, maps, options) => formParamsSwitch(formData, maps, { dateFormat, ...options });
577
588
 
589
+ const isStr = (val) => typeof val === 'string';
590
+ const NOMETHOD = Symbol('NOMETHOD');
591
+ /**
592
+ * 创建emitter形式的实例,可以通过实例封装事件对象,比如websocket,得到一个更便捷的方法,具体可参考page-communicate.js文件内容
593
+ * @param options 配置项
594
+ * @returns
595
+ */
596
+ function eventTargetEmitter(options) {
597
+ const watchers = new Map([[NOMETHOD, new Set()]]);
598
+ const { name: currentName, customHanlderCreator } = options || {};
599
+ const customHanlder = customHanlderCreator instanceof Function ? customHanlderCreator(watchers) : null;
600
+ const splitRegExp = /\|-[a-z]+-\|/;
601
+ const listenerSafeRun = (listener, ...args) => {
602
+ try {
603
+ listener(...args);
604
+ }
605
+ catch (e) {
606
+ console.error(e);
607
+ }
608
+ };
609
+ const defaultHanlder = (payload) => {
610
+ const { method, data, originEmitterName: from, targetEmitterName: to } = payload || [];
611
+ if (method && typeof method === 'string') {
612
+ const matchListeners = [];
613
+ watchers.forEach((value, key) => {
614
+ if (typeof key === 'string' && key.startsWith(method)) {
615
+ const [, eFrom,] = key.split(splitRegExp);
616
+ if (!eFrom || !from || eFrom === from) {
617
+ matchListeners.push(...value);
618
+ }
619
+ }
620
+ });
621
+ if (matchListeners.length && (!currentName || !to || currentName === to)) {
622
+ matchListeners.forEach(listener => listenerSafeRun(listener, data));
623
+ }
624
+ }
625
+ const noMethodListeners = watchers.get(NOMETHOD);
626
+ if (noMethodListeners) {
627
+ noMethodListeners.forEach(listener => listenerSafeRun(listener, data, payload));
628
+ }
629
+ };
630
+ const rootEventListener = customHanlder instanceof Function ? customHanlder : defaultHanlder;
631
+ const getFullMethodName = (method, options) => {
632
+ const { limitFrom = '', namespace = '' } = options || {};
633
+ return (limitFrom || namespace) && typeof method === 'string' ? `${method}|-from-|${limitFrom}|-ns-|${namespace}` : method;
634
+ };
635
+ const on = (method, listener, options) => {
636
+ if (typeof method === 'symbol' && method !== NOMETHOD) {
637
+ return;
638
+ }
639
+ const trueMethod = getFullMethodName(method, options);
640
+ if (!watchers.has(trueMethod)) {
641
+ watchers.set(trueMethod, new Set());
642
+ }
643
+ const listeners = watchers.get(trueMethod);
644
+ listeners?.add(listener);
645
+ };
646
+ const off = (method, callback, options) => {
647
+ if (typeof method === 'symbol' && method !== NOMETHOD) {
648
+ return;
649
+ }
650
+ const { limitFrom, namespace } = options || {};
651
+ if (namespace && !method) {
652
+ watchers.forEach((_value, key) => {
653
+ if (typeof key === 'string' && key.endsWith(namespace)) {
654
+ watchers.delete(key);
655
+ }
656
+ });
657
+ return;
658
+ }
659
+ const trueMethod = getFullMethodName(method, options);
660
+ if (!callback) {
661
+ watchers.delete(trueMethod);
662
+ return;
663
+ }
664
+ watchers.get(trueMethod)?.delete(callback);
665
+ };
666
+ const removeAllListeners = () => {
667
+ watchers.clear();
668
+ };
669
+ const createPayload = (methodOrPayload, data, target) => {
670
+ return isStr(methodOrPayload) ? {
671
+ method: methodOrPayload,
672
+ data,
673
+ ...(target && isStr(target) ? { targetEmitterName: target } : {}),
674
+ ...(currentName && isStr(currentName) ? { originEmitterName: currentName } : {})
675
+ } : methodOrPayload;
676
+ };
677
+ const emit = (...args) => {
678
+ const payload = createPayload(...args);
679
+ rootEventListener(payload);
680
+ };
681
+ /** 获取当前所有监听方法的方法名,默认仅返回函数名,设置all为true可以返回具体来源限制和命名空间字段 */
682
+ const getMethodNames = (all) => {
683
+ if (!all) {
684
+ const result = [];
685
+ watchers.forEach((_v, key) => isStr(key) && result.push(key.split(splitRegExp)));
686
+ return result;
687
+ }
688
+ const result = [];
689
+ watchers.forEach((_v, key) => isStr(key) && result.push(key));
690
+ return result;
691
+ };
692
+ const getListeners = (method, options) => {
693
+ if (typeof method === 'symbol') {
694
+ return method === NOMETHOD ? Array.from(watchers.get(NOMETHOD) || []) : [];
695
+ }
696
+ const trueMethod = getFullMethodName(method, options);
697
+ const listeners = watchers.get(trueMethod);
698
+ return listeners ? Array.from(listeners) : [];
699
+ };
700
+ return { name: currentName, rootEventListener, on, off, emit, createPayload, removeAllListeners, getMethodNames, getListeners };
701
+ }
702
+
703
+ /**
704
+ * 创建同源页面之间通信的封装实例,默认使用BroadcastChannel实现,在不支持的浏览器环境中会使用localstorage实现
705
+ * @param options 配置对象
706
+ * @returns
707
+ */
708
+ function pageCommunicate(options) {
709
+ const { messageHanlder, currentPage } = options || {};
710
+ const { emit, on, off, createPayload, removeAllListeners } = eventTargetEmitter({ name: currentPage, customHanlderCreator: messageHanlder });
711
+ const onMessage = (event) => emit(event.data);
712
+ let bc;
713
+ const ls = window.localStorage;
714
+ const channelName = 'PAGE_COMMUNICATE_CHANNEL';
715
+ if (typeof BroadcastChannel !== undefined) {
716
+ bc = new BroadcastChannel(channelName);
717
+ bc.addEventListener('message', onMessage);
718
+ }
719
+ else {
720
+ const onStorageMessage = () => {
721
+ const payload = safeJsonParse(ls.getItem(channelName) || '');
722
+ if (payload) {
723
+ emit(payload);
724
+ }
725
+ };
726
+ window.addEventListener('storage', onStorageMessage);
727
+ }
728
+ const send = (...args) => {
729
+ const payload = createPayload(...args);
730
+ if (bc) {
731
+ bc.postMessage(payload);
732
+ }
733
+ else {
734
+ const payloadWitchTs = JSON.stringify({ ...payload, ts: +new Date() });
735
+ ls.setItem(channelName, payloadWitchTs);
736
+ }
737
+ };
738
+ const destory = () => {
739
+ removeAllListeners();
740
+ if (bc) {
741
+ bc.close();
742
+ }
743
+ else {
744
+ ls.removeItem(channelName);
745
+ }
746
+ };
747
+ return { on, off, send, destory };
748
+ }
749
+
578
750
  exports.ChinaIdCardValid = ChinaIdCardValid;
751
+ exports.NOMETHOD = NOMETHOD;
579
752
  exports.array2tree = array2tree;
580
753
  exports.awaitWrapper = awaitWrapper;
581
754
  exports.byteParse = byteParse;
582
755
  exports.byteStringify = byteStringify;
583
756
  exports.checkoutBy = checkoutBy;
757
+ exports.eventTargetEmitter = eventTargetEmitter;
584
758
  exports.filterNullable = filterNullable;
585
759
  exports.formParamsSwitch = formParamsSwitch;
586
760
  exports.formParamsSwitchCreator = formParamsSwitchCreator;
@@ -589,6 +763,7 @@ exports.isNullable = isNullable;
589
763
  exports.mapToObject = mapToObject;
590
764
  exports.maskData = maskData;
591
765
  exports.objType = objType;
766
+ exports.pageCommunicate = pageCommunicate;
592
767
  exports.pickRenameKeys = pickRenameKeys;
593
768
  exports.safeJsonParse = safeJsonParse;
594
769
  exports.switchNullToUndefined = switchNullToUndefined;
package/dist/index.min.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.6.0
2
+ * @wxhccc/es-util v1.7.0
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
6
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Smartfetch={})}(this,(function(e){"use strict";const{hasOwnProperty:t}=Object.prototype;function n(e,t=[]){return{[e]:t}}const r=/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i;const i={telphone:{startCharIndex:-8,endCharIndex:-5},idcard:{startCharIndex:-12,endCharIndex:-5}};const{hasOwnProperty:c,toString:o}=Object.prototype,s=e=>{const t=o.call(e).match(/^\[object (.*)\]$/);return t?t[1]:""};async function a(e){try{return[null,await e]}catch(e){return[e,void 0]}}const l={};function u(e,t){const n=function(e){return e?e._isVue||e.$&&e.$.vnode?"vue":"setState"in e?"react":"unknown":"unknown"}(this),r="unknown"!==n,i=r?this:l,o="react"===n?"state":"",u=o?i[o]:i,{wrap:f,lock:p,syncRefHandle:y,manualUnlock:d}="boolean"==typeof t?{wrap:t}:{...t};let h,b,j=[],g=!1,m=!1;const O=(e,t)=>!!e&&c.call(e,t),x=e=>"Object"===s(e),B=e=>{j.length?r?((e,t,r)=>{if("vue"===n&&i.$set&&!O(e,t[0]))return;const{$set:c=((e,t,n)=>{e[t]=n})}=i,o="react"===n,s=o?{...e}:e;let a=s,l=!1;for(let e=0;e<t.length;e++){const n=t[e],i=O(a,n);if(e===t.length-1){const e="boolean"==typeof a[n];l=!i||e,l&&c(a,n,r)}else{if(!i&&c(a,n,{}),!x(a[n]))break;o&&(a[n]={...a[n]}),a=a[n]}}o&&l&&i.setState({[t[0]]:s[t[0]]})})(u,j,e):l[p]=e:(b&&(b[0][b[1]]=e),h&&h(e))},k=()=>b?b[0][b[1]]:r||"string"!=typeof p?((e,t)=>{let n=!1;if(e&&x(e)&&Array.isArray(t)&&t.length){let r=e;for(let e=0;e<t.length;e++){const i=t[e];if("object"!=typeof r||!O(r,i))break;r=r[i],e===t.length-1&&(n="boolean"==typeof r&&r)}}return n})(u,j):u[p];if(p){const e=e=>Array.isArray(e)&&2===e.length;"string"==typeof p?j=p.split("."):e(p)?b=p:"function"==typeof p&&(h=p,e(y)&&(b=y)),g=j.length>0||!!b||!!h,g&&(m=k())}let A;A="function"==typeof e?m?(()=>{const e=Promise.resolve(void 0);return Object.assign(e,{then(...t){const[n]=t;return 2===t.length&&"function"==typeof n?n(void 0):e},catch:t=>e,finally:()=>e})})():f?a(e()):e():f?a(e):e;const K=()=>B(!1);return Object.defineProperties(A,{__lockValue:{get:k},_checkLockKey:{value:e=>l[e]},unlock:{value:K}}),g&&!m&&(B(!0),!d&&A.finally(K)),A}const f=Object.defineProperty(u,"_checkLockKey",{value:e=>l[e]}),p={install(e,t="$wp"){e.config&&"globalProperties"in e.config?e.config.globalProperties[t]=u:e.prototype[t]=u}};const y=(e,t)=>{const n={};return Object.keys(e).forEach((r=>{const i=e[r];""!==i&&null!=i&&(n[r]=t&&"[object Object]"===Object.prototype.toString.call(i)?y(i):i)})),n},{toString:d}=Object.prototype,h=e=>{if(null!==e)return Array.isArray(e)?e.map(h):("[object Object]"===d.call(e)&&Object.keys(e).forEach((t=>{e[t]=h(e[t])})),e)},b=(e,t,n)=>{const r=Object.keys(t),i={},c={};Object.keys(e).forEach((t=>{r.includes(t)?i[t]=e[t]:c[t]=e[t]}));const o=Object.keys(i);if(0===o.length)return e;const{filterNullable:s,dateFormat:a}={filterNullable:!0,...n},l=o.reduce(((e,n)=>{const r=i[n],c=t[n];if(!r||!c)return e;if("join"===c||"pop"===c)Array.isArray(r)&&r.length&&(e[n]="join"===c?r.join(","):r.slice(-1)[0]);else if(2===c.length||3===c.length){if(!r||2!==r.length)return e;const[t,n,i]=c,[o,s]=r;Object.assign(e,{[t]:a instanceof Function?a(o,i):o,[n]:a instanceof Function?a(s,i):s})}return e}),{}),u={...c,...l};return s?y(u):u};e.ChinaIdCardValid=function(e){const t=e.toString().toUpperCase();return r.test(t)&&["11","12","13","14","15","21","22","23","31","32","33","34","35","36","37","41","42","43","44","45","46","50","51","52","53","54","61","62","63","64","65","71","81","82","91"].includes(t.substr(0,2))&&(()=>{if(18===t.length){const e=t.split(""),n=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2],r=[1,0,"X",9,8,7,6,5,4,3,2];let i=0,c=0,o=0;for(let t=0;t<17;t++)c=parseInt(e[t]),o=n[t],i+=c*o;return r[i%11].toString()===e[17]}return!0})()},e.array2tree=function(e,r={}){const{primaryKey:i,parentKey:c,childrenKey:o,createRoot:s,parentRefKey:a}=Object.assign({primaryKey:"id",parentKey:"pid",childrenKey:"children",createRoot:!1,parentRefKey:!1},r),l=a&&("string"==typeof a?a:"_parent");let u={},f=[];return Array.isArray(e)&&e.forEach((e=>{!t.call(u,e[i])&&(u[e[i]]=Object.assign({},e,n(o))),t.call(u,e[c])&&u[e[c]][o].push(Object.assign(u[e[i]],l?{[l]:u[e[c]]}:{})),!e[c]&&f.push(u[e[i]])})),"function"==typeof s?s(f):s?{[o]:f}:f},e.awaitWrapper=a,e.byteParse=function(e,t={}){},e.byteStringify=function(e,t){const n=Object.assign({standard:"jedec",unitLvl:"auto",precision:1,detail:!1},t),{standard:r,unitLvl:i,precision:c,detail:o}=n;let s=parseFloat(e);if(!Number.isFinite(s))return;const a=s<0?-1:1;s=Math.abs(s);const{base:l,unitMap:u}=((e,t)=>{const n={B:{expMax:0,units:{metric:"B",iec:"B",jedec:"B"}},K:{expMax:1,units:{metric:"kB",iec:"KiB",jedec:"KB"}},M:{expMax:2,units:{metric:"MB",iec:"MiB",jedec:"MB"}},G:{expMax:3,units:{metric:"GB",iec:"GiB",jedec:"GB"}},T:{expMax:4,units:{metric:"TB",iec:"TiB",jedec:"TB"}},P:{expMax:5,units:{metric:"PB",iec:"PiB",jedec:"PB"}},E:{expMax:6,units:{metric:"EB",iec:"EiB",jedec:"EB"}},Z:{expMax:7,units:{metric:"ZB",iec:"ZiB",jedec:"ZB"}},Y:{expMax:8,units:{metric:"YB",iec:"YiB",jedec:"YB"}}},r={metric:1e3,iec:1024,jedec:1024};return{base:r[e]||r.jedec,unitMap:n[t]||Object.values(n)}})(r,i),f=e=>Number.isInteger(e)?e:e.toFixed(c);let p="",y=0;if(Array.isArray(u))u.some((e=>{const t=Math.pow(l,e.expMax),n=s/t;return!(n>l)&&(p=e.units[r],y=f(n*a),!0)}));else{const e=Math.pow(l,u.expMax);p=u.units[r];y=f(s/e*a)}return o?{value:y,unit:p}:`${y} ${p}`},e.checkoutBy=function(e,t,n){return e instanceof Object?Array.isArray(t)?t.map((t=>e[t])):t&&t instanceof Object?Object.keys(t).map((r=>e[r]instanceof Object&&t[r]instanceof Object?n?n({},e[r],t[r]):Object.assign({},e[r],t[r]):t[r]||e[r])):Object.values(e):[]},e.filterNullable=y,e.formParamsSwitch=b,e.formParamsSwitchCreator=e=>(t,n,r)=>b(t,n,{dateFormat:e,...r}),e.formulaValidate=function(e,t){return e=e.replace(/\s/g,""),!/[+\-*/]{2,}/.test(e)&&!/\(\)/.test(e)&&!/\([+\-*/]/.test(e)&&!/[+\-*/]\)/.test(e)&&!/[^+\-*/]\(/.test(e)&&!/\)[^+\-*/]/.test(e)&&(()=>{let t=[];for(let n,r=0;r<e.length;r++)if(n=e.charAt(r),"("===n)t.push("(");else if(")"===n){if(!(t.length>0))return!1;t.pop()}return!t.length})()&&(!Array.isArray(t)||(n=t,e.replace(/[()+\-*/]{1,}/g,"`").split("`").every((e=>!/[A-Z]/i.test(e)||n.includes(e)))));var n},e.isNullable=e=>""===e||null==e,e.mapToObject=function(e,t="key",n="value"){let r={};return Array.isArray(e)&&t&&n&&[t,n].every((e=>["string","function"].includes(typeof e)))&&e.forEach(((e,i)=>{const c="string"==typeof t?e[t]:t(e,i),o="string"==typeof n?e[n]:n(e,i);["string","number"].includes(typeof c)&&(r[c]=o)})),r},e.maskData=function(e,t){if("string"!=typeof e||!e)return"";const n=t&&t.mode&&i[t.mode]?i[t.mode]:{},{maskWith:r,startCharIndex:c=0,endCharIndex:o,startFrom:s,endUntil:a}={maskWith:"*",...n,...t};let l=e,u="",f="";const p=s?e.indexOf(s):-1;if(p>-1){const t=p+s.length;l=l.slice(t),u=e.slice(0,t)}const y=a?e.lastIndexOf(a):-1;y>-1&&(l=l.slice(0,y),f=e.slice(y));const d=l.split(""),h=[u],b=d.length,j=[c>=0?c:b+c,void 0!==o?o>=0?o:b+o:b-1];let[g,m]=j;return m=m>0&&m<b?m:b-1,g=g>=0&&g<=m?g:0,d.forEach(((e,t)=>{h.push(t>=g&&t<=m?r:e)})),h.push(f),h.join("")},e.objType=s,e.pickRenameKeys=function(e,t){if(!(e&&e instanceof Object&&t&&t instanceof Object))return;let n={};for(let r in e)r in t&&(n[t[r]]=e[r]);return n},e.safeJsonParse=function(e="",t){try{return JSON.parse(e)}catch(e){return t}},e.switchNullToUndefined=h,e.tree2array=function(e,t={}){const{primaryKey:r,parentKey:i,childrenKey:c,hasParentKey:o,returnObject:s}=Object.assign({hasParentKey:!0,primaryKey:"id",parentKey:"pid",childrenKey:"children",returnObject:!1},t);let a=s?{}:[];return Array.isArray(e)||"object"==typeof e?(function e(t,n,l=!1){let u=o?{}:{[i]:n};if(!l){const e=Object.assign(u,function(e,t){let n={};for(let r in e)r!==t&&(n[r]=e[r]);return n}(t,c));s?a[t[r]]=e:a.push(e)}Array.isArray(t[c])&&t[c].length&&t[c].forEach((n=>e(n,t[r])))}(Array.isArray(e)?n(c,e):e,null,!0),a):a},e.wp=f,e.wpVuePlugin=p,Object.defineProperty(e,"__esModule",{value:!0})}));
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 o=e=>"[object Object]"===Object.prototype.toString.call(e);const i={telphone:{startCharIndex:-8,endCharIndex:-5},idcard:{startCharIndex:-12,endCharIndex:-5}};const{hasOwnProperty:s,toString:c}=Object.prototype,a=e=>{const t=c.call(e).match(/^\[object (.*)\]$/);return t?t[1]:""};async function l(e){try{return[null,await e]}catch(e){return[e,void 0]}}const u={};function f(e,t){const n=function(e){return e?e._isVue||e.$&&e.$.vnode?"vue":"setState"in e?"react":"unknown":"unknown"}(this),r="unknown"!==n,o=r?this:u,i="react"===n?"state":"",c=i?o[i]:o,{wrap:f,lock:p,syncRefHandle:y,manualUnlock:d}="boolean"==typeof t?{wrap:t}:{...t};let h,m,g=[],b=!1,j=!1;const O=(e,t)=>!!e&&s.call(e,t),x=e=>"Object"===a(e),A=e=>{g.length?r?((e,t,r)=>{if("vue"===n&&o.$set&&!O(e,t[0]))return;const{$set:i=((e,t,n)=>{e[t]=n})}=o,s="react"===n,c=s?{...e}:e;let a=c,l=!1;for(let e=0;e<t.length;e++){const n=t[e],o=O(a,n);if(e===t.length-1){const e="boolean"==typeof a[n];l=!o||e,l&&i(a,n,r)}else{if(!o&&i(a,n,{}),!x(a[n]))break;s&&(a[n]={...a[n]}),a=a[n]}}s&&l&&o.setState({[t[0]]:c[t[0]]})})(c,g,e):u[p]=e:(m&&(m[0][m[1]]=e),h&&h(e))},B=()=>m?m[0][m[1]]:r||"string"!=typeof p?((e,t)=>{let n=!1;if(e&&x(e)&&Array.isArray(t)&&t.length){let r=e;for(let e=0;e<t.length;e++){const o=t[e];if("object"!=typeof r||!O(r,o))break;r=r[o],e===t.length-1&&(n="boolean"==typeof r&&r)}}return n})(c,g):c[p];if(p){const e=e=>Array.isArray(e)&&2===e.length;"string"==typeof p?g=p.split("."):e(p)?m=p:"function"==typeof p&&(h=p,e(y)&&(m=y)),b=g.length>0||!!m||!!h,b&&(j=B())}let v;v="function"==typeof e?j?(()=>{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?l(e()):e():f?l(e):e;const E=()=>A(!1);return Object.defineProperties(v,{__lockValue:{get:B},_checkLockKey:{value:e=>u[e]},unlock:{value:E}}),b&&!j&&(A(!0),!d&&v.finally(E)),v}const p=Object.defineProperty(f,"_checkLockKey",{value:e=>u[e]}),y={install(e,t="$wp"){e.config&&"globalProperties"in e.config?e.config.globalProperties[t]=f:e.prototype[t]=f}};function d(e="",t){try{return JSON.parse(e)}catch(e){return t}}const h=(e,t)=>{const n={};return Object.keys(e).forEach((r=>{const o=e[r];""!==o&&null!=o&&(n[r]=t&&"[object Object]"===Object.prototype.toString.call(o)?h(o):o)})),n},{toString:m}=Object.prototype,g=e=>{if(null!==e)return Array.isArray(e)?e.map(g):("[object Object]"===m.call(e)&&Object.keys(e).forEach((t=>{e[t]=g(e[t])})),e)},b=(e,t,n)=>{const r=Object.keys(t),o={},i={};Object.keys(e).forEach((t=>{r.includes(t)?o[t]=e[t]:i[t]=e[t]}));const s=Object.keys(o);if(0===s.length)return e;const{filterNullable:c,dateFormat:a}={filterNullable:!0,...n},l=s.reduce(((e,n)=>{const r=o[n],i=t[n];if(!r||!i)return e;if("join"===i||"pop"===i)Array.isArray(r)&&r.length&&(e[n]="join"===i?r.join(","):r.slice(-1)[0]);else if(2===i.length||3===i.length){if(!r||2!==r.length)return e;const[t,n,o]=i,[s,c]=r;Object.assign(e,{[t]:a instanceof Function?a(s,o):s,[n]:a instanceof Function?a(c,o):c})}return e}),{}),u={...i,...l};return c?h(u):u},j=e=>"string"==typeof e,O=Symbol("NOMETHOD");function x(e){const t=new Map([[O,new Set]]),{name:n,customHanlderCreator:r}=e||{},o=r instanceof Function?r(t):null,i=/\|-[a-z]+-\|/,s=(e,...t)=>{try{e(...t)}catch(e){console.error(e)}},c=o instanceof Function?o:e=>{const{method:r,data:o,originEmitterName:c,targetEmitterName:a}=e||[];if(r&&"string"==typeof r){const e=[];t.forEach(((t,n)=>{if("string"==typeof n&&n.startsWith(r)){const[,r]=n.split(i);r&&c&&r!==c||e.push(...t)}})),!e.length||n&&a&&n!==a||e.forEach((e=>s(e,o)))}const l=t.get(O);l&&l.forEach((t=>s(t,o,e)))},a=(e,t)=>{const{limitFrom:n="",namespace:r=""}=t||{};return(n||r)&&"string"==typeof e?`${e}|-from-|${n}|-ns-|${r}`:e},l=(e,t,r)=>j(e)?{method:e,data:t,...r&&j(r)?{targetEmitterName:r}:{},...n&&j(n)?{originEmitterName:n}:{}}:e;return{name:n,rootEventListener:c,on:(e,n,r)=>{if("symbol"==typeof e&&e!==O)return;const o=a(e,r);t.has(o)||t.set(o,new Set);t.get(o)?.add(n)},off:(e,n,r)=>{if("symbol"==typeof e&&e!==O)return;const{limitFrom:o,namespace:i}=r||{};if(i&&!e)return void t.forEach(((e,n)=>{"string"==typeof n&&n.endsWith(i)&&t.delete(n)}));const s=a(e,r);n?t.get(s)?.delete(n):t.delete(s)},emit:(...e)=>{const t=l(...e);c(t)},createPayload:l,removeAllListeners:()=>{t.clear()},getMethodNames:e=>{if(!e){const e=[];return t.forEach(((t,n)=>j(n)&&e.push(n.split(i)))),e}const n=[];return t.forEach(((e,t)=>j(t)&&n.push(t))),n},getListeners:(e,n)=>{if("symbol"==typeof e)return e===O?Array.from(t.get(O)||[]):[];const r=a(e,n),o=t.get(r);return o?Array.from(o):[]}}}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 o=0,i=0,s=0;for(let t=0;t<17;t++)i=parseInt(e[t]),s=n[t],o+=i*s;return r[o%11].toString()===e[17]}return!0})()},e.NOMETHOD=O,e.array2tree=function(e,r={}){const{primaryKey:o,parentKey:i,childrenKey:s,createRoot:c,parentRefKey:a}={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[o])&&(u[e[o]]=Object.assign({},e,n(s))),t.call(u,e[i])&&u[e[i]][s].push(Object.assign(u[e[o]],l?{[l]:u[e[i]]}:{})),!e[i]&&f.push(u[e[o]])})),c instanceof Function?c(f):c?{[s]:f}:f},e.awaitWrapper=l,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:o,precision:i,detail:s}=n;let c=parseFloat(e);if(!Number.isFinite(c))return;const a=c<0?-1:1;c=Math.abs(c);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,o),f=e=>Number.isInteger(e)?e:e.toFixed(i);let p="",y=0;if(Array.isArray(u))u.some((e=>{const t=Math.pow(l,e.expMax),n=c/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(c/e*a)}return s?{value:y,unit:p}:`${y} ${p}`},e.checkoutBy=function(e,t,n){return o(e)?Array.isArray(t)?t.map((t=>e[t])):t&&o(t)?Object.keys(t).map((r=>o(e[r])&&o(t[r])?n?n({},e[r],t[r]):Object.assign({},e[r],t[r]):t[r]||e[r])):Object.values(e):[]},e.eventTargetEmitter=x,e.filterNullable=h,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"){const r={};return Array.isArray(e)&&t&&n&&[t,n].every((e=>["string","function"].includes(typeof e)))&&e.forEach(((e,o)=>{const i="string"==typeof t?e[t]:t(e,o),s="string"==typeof n?e[n]:n(e,o);["string","number"].includes(typeof i)&&(r[i]=s)})),r},e.maskData=function(e,t){if("string"!=typeof e||!e)return"";const n=t&&t.mode&&i[t.mode]?i[t.mode]:{},{maskWith:r,startCharIndex:o=0,endCharIndex:s,startFrom:c,endUntil:a}={maskWith:"*",...n,...t};let l=e,u="",f="";const p=c?e.indexOf(c):-1;if(p>-1){const t=p+c.length;l=l.slice(t),u=e.slice(0,t)}const y=a?e.lastIndexOf(a):-1;y>-1&&(l=l.slice(0,y),f=e.slice(y));const d=l.split(""),h=[u],m=d.length,g=[o>=0?o:m+o,void 0!==s?s>=0?s:m+s:m-1];let[b,j]=g;return j=j>0&&j<m?j:m-1,b=b>=0&&b<=j?b:0,d.forEach(((e,t)=>{h.push(t>=b&&t<=j?r:e)})),h.push(f),h.join("")},e.objType=a,e.pageCommunicate=function(e){const{messageHanlder:t,currentPage:n}=e||{},{emit:r,on:o,off:i,createPayload:s,removeAllListeners:c}=x({name:n,customHanlderCreator:t}),a=e=>r(e.data);let l;const u=window.localStorage,f="PAGE_COMMUNICATE_CHANNEL";if(void 0!==typeof BroadcastChannel)l=new BroadcastChannel(f),l.addEventListener("message",a);else{const e=()=>{const e=d(u.getItem(f)||"");e&&r(e)};window.addEventListener("storage",e)}return{on:o,off:i,send:(...e)=>{const t=s(...e);if(l)l.postMessage(t);else{const e=JSON.stringify({...t,ts:+new Date});u.setItem(f,e)}},destory:()=>{c(),l?l.close():u.removeItem(f)}}},e.pickRenameKeys=function(e,t){if(!(e&&o(e)&&t&&o(t)))return;let n={};for(let r in e)r in t&&(n[t[r]]=e[r]);return n},e.safeJsonParse=d,e.switchNullToUndefined=g,e.tree2array=function(e,t={}){const{primaryKey:r,parentKey:o,childrenKey:i,hasParentKey:s,returnObject:c}=Object.assign({hasParentKey:!0,primaryKey:"id",parentKey:"pid",childrenKey:"children",returnObject:!1},t);let a=c?{}:[];return Array.isArray(e)||"object"==typeof e?(function e(t,n,l=!1){let u=s?{}:{[o]: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,i));c?a[t[r]]=e:a.push(e)}Array.isArray(t[i])&&t[i].length&&t[i].forEach((n=>e(n,t[r])))}(Array.isArray(e)?n(i,e):e,null,!0),a):a},e.wp=p,e.wpVuePlugin=y,Object.defineProperty(e,"__esModule",{value:!0})}));
@@ -1,6 +1,4 @@
1
- declare type Obj = {
2
- [key: string]: any;
3
- };
1
+ import { AnyObject } from './types';
4
2
  /**
5
3
  * translate object array to key-value map object
6
4
  *
@@ -11,7 +9,8 @@ declare type Obj = {
11
9
  interface PropHandler {
12
10
  (item: any, index: number): string;
13
11
  }
14
- export declare function mapToObject(objectArray: any[], keyProp?: string | PropHandler, valueProp?: string | PropHandler): Obj;
12
+ export declare function mapToObject(objectArray: AnyObject[], keyProp?: string | PropHandler, valueProp?: string | PropHandler): Record<string, string | number>;
13
+ declare type MergeFn = <T>(...args: T[]) => T;
15
14
  /**
16
15
  * checkout values form object as an array
17
16
  *
@@ -19,15 +18,14 @@ export declare function mapToObject(objectArray: any[], keyProp?: string | PropH
19
18
  * @param {string[] | Object} keys
20
19
  * @param {string} valueProp
21
20
  */
22
- declare type MergeFn = <T>(...args: T[]) => T;
23
- export declare function checkoutBy(object: Obj, keys?: string[] | Obj, mergeFn?: MergeFn): any[];
21
+ export declare function checkoutBy(object: AnyObject, keys?: string[] | AnyObject, mergeFn?: MergeFn): any[];
24
22
  /**
25
23
  * pick and rename object values
26
24
  *
27
25
  * @param {Object} object
28
26
  * @param {Object} keysMap
29
27
  */
30
- export declare function pickRenameKeys(object: Obj, keysMap: {
28
+ export declare function pickRenameKeys(object: AnyObject, keysMap: {
31
29
  [key: string]: string;
32
- }): Obj | undefined;
30
+ }): AnyObject | undefined;
33
31
  export {};
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.6.0
2
+ * @wxhccc/es-util v1.7.0
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -8,7 +8,7 @@
8
8
  Object.defineProperty(exports, '__esModule', { value: true });
9
9
 
10
10
  function mapToObject(objectArray, keyProp = 'key', valueProp = 'value') {
11
- let result = {};
11
+ const result = {};
12
12
  Array.isArray(objectArray) && keyProp && valueProp
13
13
  && [keyProp, valueProp].every(val => ['string', 'function'].includes(typeof val))
14
14
  && objectArray.forEach((item, index) => {
@@ -18,15 +18,24 @@ function mapToObject(objectArray, keyProp = 'key', valueProp = 'value') {
18
18
  });
19
19
  return result;
20
20
  }
21
+ const isObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]';
22
+ /**
23
+ * checkout values form object as an array
24
+ *
25
+ * @param {Object} object
26
+ * @param {string[] | Object} keys
27
+ * @param {string} valueProp
28
+ */
21
29
  function checkoutBy(object, keys, mergeFn) {
22
- if (!(object instanceof Object))
30
+ if (!isObject(object)) {
23
31
  return [];
32
+ }
24
33
  if (Array.isArray(keys)) {
25
- return keys.map(item => (object[item]));
34
+ return keys.map(item => object[item]);
26
35
  }
27
- else if (keys && keys instanceof Object) {
28
- return Object.keys(keys).map(item => (object[item] instanceof Object && keys[item] instanceof Object)
29
- ? (mergeFn ? mergeFn({}, object[item], keys[item]) : Object.assign({}, object[item], keys[item]))
36
+ else if (keys && isObject(keys)) {
37
+ return Object.keys(keys).map(item => (isObject(object[item]) && isObject(keys[item]))
38
+ ? (mergeFn ? mergeFn({}, (object)[item], (keys)[item]) : Object.assign({}, object[item], keys[item]))
30
39
  : (keys[item] || object[item]));
31
40
  }
32
41
  return Object.values(object);
@@ -38,8 +47,9 @@ function checkoutBy(object, keys, mergeFn) {
38
47
  * @param {Object} keysMap
39
48
  */
40
49
  function pickRenameKeys(object, keysMap) {
41
- if (!object || !(object instanceof Object) || !keysMap || !(keysMap instanceof Object))
50
+ if (!object || !isObject(object) || !keysMap || !isObject(keysMap)) {
42
51
  return;
52
+ }
43
53
  let result = {};
44
54
  for (let i in object) {
45
55
  (i in keysMap) && (result[keysMap[i]] = object[i]);
@@ -0,0 +1,27 @@
1
+ import { EventPayload as OrgEventPayload, ConfigOptions as OrgCfgOps } from './event-target-emitter';
2
+ export { NOMETHOD } from './event-target-emitter';
3
+ export interface PcEventPayload<T = any> extends Omit<OrgEventPayload, 'originEmitterName' | 'targetEmitterName'> {
4
+ /** 从哪个页面发送 */
5
+ from?: string;
6
+ /** 指定哪个页面接收 */
7
+ to?: string;
8
+ }
9
+ export interface PcConfigOptions {
10
+ /** 当前页面name */
11
+ currentPage?: string;
12
+ /** 自定义消息处理逻辑 */
13
+ messageHanlder?: OrgCfgOps['customHanlderCreator'];
14
+ }
15
+ /**
16
+ * 创建同源页面之间通信的封装实例,默认使用BroadcastChannel实现,在不支持的浏览器环境中会使用localstorage实现
17
+ * @param options 配置对象
18
+ * @returns
19
+ */
20
+ export declare function pageCommunicate(options?: PcConfigOptions): {
21
+ on: <T>(method: string | symbol, listener: (data: T) => any, options?: import("./event-target-emitter").BindOptions | undefined) => void;
22
+ off: (method: string | symbol, callback?: import("./types").AnyFunction<any> | undefined, options?: import("./event-target-emitter").BindOptions | undefined) => void;
23
+ send: (methodOrPayload: string | OrgEventPayload<any>, data?: any, target?: string | undefined) => void;
24
+ destory: () => void;
25
+ };
26
+ export declare type BccnInstance = ReturnType<typeof pageCommunicate>;
27
+ export default pageCommunicate;
@@ -0,0 +1,70 @@
1
+ /*!
2
+ * @wxhccc/es-util v1.7.0
3
+ * (c) 2022 wxhccc
4
+ * @license MIT
5
+ */
6
+ 'use strict';
7
+
8
+ Object.defineProperty(exports, '__esModule', { value: true });
9
+
10
+ var eventTargetEmitter = require('./event-target-emitter.js');
11
+
12
+ function safeJsonParse(json = '', faileValue) {
13
+ try {
14
+ return JSON.parse(json);
15
+ }
16
+ catch (_e) {
17
+ return faileValue;
18
+ }
19
+ }
20
+
21
+ /**
22
+ * 创建同源页面之间通信的封装实例,默认使用BroadcastChannel实现,在不支持的浏览器环境中会使用localstorage实现
23
+ * @param options 配置对象
24
+ * @returns
25
+ */
26
+ function pageCommunicate(options) {
27
+ const { messageHanlder, currentPage } = options || {};
28
+ const { emit, on, off, createPayload, removeAllListeners } = eventTargetEmitter.eventTargetEmitter({ name: currentPage, customHanlderCreator: messageHanlder });
29
+ const onMessage = (event) => emit(event.data);
30
+ let bc;
31
+ const ls = window.localStorage;
32
+ const channelName = 'PAGE_COMMUNICATE_CHANNEL';
33
+ if (typeof BroadcastChannel !== undefined) {
34
+ bc = new BroadcastChannel(channelName);
35
+ bc.addEventListener('message', onMessage);
36
+ }
37
+ else {
38
+ const onStorageMessage = () => {
39
+ const payload = safeJsonParse(ls.getItem(channelName) || '');
40
+ if (payload) {
41
+ emit(payload);
42
+ }
43
+ };
44
+ window.addEventListener('storage', onStorageMessage);
45
+ }
46
+ const send = (...args) => {
47
+ const payload = createPayload(...args);
48
+ if (bc) {
49
+ bc.postMessage(payload);
50
+ }
51
+ else {
52
+ const payloadWitchTs = JSON.stringify({ ...payload, ts: +new Date() });
53
+ ls.setItem(channelName, payloadWitchTs);
54
+ }
55
+ };
56
+ const destory = () => {
57
+ removeAllListeners();
58
+ if (bc) {
59
+ bc.close();
60
+ }
61
+ else {
62
+ ls.removeItem(channelName);
63
+ }
64
+ };
65
+ return { on, off, send, destory };
66
+ }
67
+
68
+ exports.NOMETHOD = eventTargetEmitter.NOMETHOD;
69
+ exports.default = pageCommunicate;
70
+ exports.pageCommunicate = pageCommunicate;
package/dist/promise.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.6.0
2
+ * @wxhccc/es-util v1.7.0
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -0,0 +1,4 @@
1
+ export declare type AnyObject = {
2
+ [key: string]: any;
3
+ };
4
+ export declare type AnyFunction<T = any> = (...args: any[]) => T;
package/dist/validate.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.6.0
2
+ * @wxhccc/es-util v1.7.0
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.6.0
2
+ * @wxhccc/es-util v1.7.0
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@wxhccc/es-util",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "description": "A library that contains some useful methods",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.esm.js",
7
7
  "unpkg": "dist/index.min.js",
8
- "types": "types/index.d.ts",
8
+ "types": "dist/index.d.ts",
9
9
  "scripts": {
10
10
  "start": "npm run dev",
11
11
  "test": "jest",
@@ -61,8 +61,7 @@
61
61
  "vue": "^3.0.11"
62
62
  },
63
63
  "files": [
64
- "dist",
65
- "types"
64
+ "dist"
66
65
  ],
67
66
  "dependencies": {}
68
67
  }
@@ -1,49 +0,0 @@
1
- export interface Node {
2
- [key: string]: any;
3
- }
4
- export interface TreeNode {
5
- [key: string]: any;
6
- }
7
- interface Options {
8
- primaryKey?: string;
9
- parentKey?: string;
10
- childrenKey?: string;
11
- }
12
- interface TreeOptions extends Options {
13
- createRoot?: boolean | ((nodes: TreeNode[]) => any);
14
- parentRefKey?: boolean | string;
15
- }
16
- interface NodeOptions extends Options {
17
- hasParentKey?: boolean;
18
- returnObject?: boolean;
19
- }
20
- declare type Tree = TreeNode[] | {
21
- [children: string]: TreeNode[];
22
- };
23
- /**
24
- * translate array to tree
25
- * @param {Array} array the node array need to be translate
26
- * @param {Object} options the options
27
- * @param {string} primaryKey the primary key of node
28
- * @param {string} parentKey the parent's key of node
29
- * @param {string} childrenKey the child's key of node
30
- * @param {boolean | Function} createNode whether create root node, or function which can return root node
31
- * @param {boolean | string} parentRefKey parent reference key of node
32
- */
33
- export declare function array2tree(array: Node[], options?: TreeOptions): Tree;
34
- declare type Nodes = Node[];
35
- declare type NodeMap = {
36
- [id: string]: Node;
37
- };
38
- /**
39
- * translate tree to array
40
- * @param {Array/Object} tree the node tree need to be translate
41
- * @param {Object} options the options
42
- * @param {string} primaryKey the primary key of tree node
43
- * @param {string} parentKey the parent's key of tree node
44
- * @param {string} childrenKey the child's key of tree node
45
- * @param {boolean} hasParentKey whether create parent id in node
46
- * @param {boolean} returnObject whether return object or array
47
- */
48
- export declare function tree2array(tree: Tree, options?: NodeOptions): NodeMap | Nodes;
49
- export {};
package/types/index.d.ts DELETED
@@ -1,6 +0,0 @@
1
- export * from './array-tree-switch';
2
- export * from './validate';
3
- export * from './object-array';
4
- export * from './value-string-switch';
5
- export * from './promise';
6
- export * from './optional';
@@ -1,33 +0,0 @@
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,50 +0,0 @@
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 {};
@@ -1,44 +0,0 @@
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>;
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;
41
- export declare const wpVuePlugin: {
42
- install(appOrVue: any, key?: string): void;
43
- };
44
- export {};
@@ -1,2 +0,0 @@
1
- export declare function ChinaIdCardValid(idNo: string): boolean;
2
- export declare function formulaValidate(string: string, variables?: string[]): boolean;
@@ -1,12 +0,0 @@
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 {};
@@ -1,2 +0,0 @@
1
- export * from './byte-string';
2
- export * from './mask-data';
@@ -1,22 +0,0 @@
1
- interface MaskDataOptions {
2
- /** 替换的字符,默认为* */
3
- maskWith?: string;
4
- /** 起始字符索引,为负数时从字符串结尾起倒数第几个数开始 */
5
- startCharIndex?: number;
6
- /** 结束字符索引,包含在处理字符内,缺省时会替换到字符串结尾,为负数时从字符串结尾起倒数第几个数开始 */
7
- endCharIndex?: number;
8
- /** 待处理字符串起始处理字符(串),不包含在待处理片段内 */
9
- startFrom?: string;
10
- /** 待处理字符串结束处理字符(串),不包含在待处理片段内 */
11
- endUntil?: string;
12
- /** 内置的默认的的处理模式,会预设一些属性值,属性值可以被覆盖 */
13
- mode?: 'telphone' | 'idcard';
14
- }
15
- /**
16
- * 对给定的字符串进行脱敏处理
17
- * @param data 需要处理的字符串
18
- * @param options 配置参数对象
19
- * @returns
20
- */
21
- export declare function maskData(data: string, options?: MaskDataOptions): string;
22
- export {};