@wxhccc/es-util 1.5.1 → 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 +22 -0
- package/dist/event-target-emitter.d.ts +45 -0
- package/dist/event-target-emitter.js +126 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.esm.js +236 -18
- package/dist/index.js +240 -17
- package/dist/index.min.js +3 -3
- package/dist/object-array.d.ts +6 -8
- package/dist/object-array.js +19 -9
- package/dist/optional.d.ts +8 -3
- package/dist/page-communicate.d.ts +27 -0
- package/dist/page-communicate.js +70 -0
- package/dist/promise.js +2 -2
- package/dist/types.d.ts +4 -0
- package/dist/validate.js +2 -2
- package/dist/value-string-switch/index.d.ts +1 -0
- package/dist/value-string-switch/mask-data.d.ts +22 -0
- package/dist/value-string-switch.js +47 -2
- package/package.json +5 -5
- package/types/array-tree-switch.d.ts +0 -49
- package/types/index.d.ts +0 -6
- package/types/object-array.d.ts +0 -33
- package/types/optional.d.ts +0 -45
- package/types/promise.d.ts +0 -44
- package/types/validate.d.ts +0 -2
- package/types/value-string-switch/byte-string.d.ts +0 -12
- package/types/value-string-switch/index.d.ts +0 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @wxhccc/es-util v1.
|
|
3
|
-
* (c)
|
|
2
|
+
* @wxhccc/es-util v1.7.0
|
|
3
|
+
* (c) 2022 wxhccc
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
6
6
|
'use strict';
|
|
@@ -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 } =
|
|
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
|
-
|
|
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 (
|
|
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
|
-
|
|
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
|
|
177
|
+
if (!isObject(object)) {
|
|
169
178
|
return [];
|
|
179
|
+
}
|
|
170
180
|
if (Array.isArray(keys)) {
|
|
171
|
-
return keys.map(item =>
|
|
181
|
+
return keys.map(item => object[item]);
|
|
172
182
|
}
|
|
173
|
-
else if (keys && keys
|
|
174
|
-
return Object.keys(keys).map(item => (object[item]
|
|
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
|
|
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]);
|
|
@@ -253,6 +264,50 @@ function byteStringify(byteNum, options) {
|
|
|
253
264
|
function byteParse(byteStr, options = {}) {
|
|
254
265
|
}
|
|
255
266
|
|
|
267
|
+
const modeIndexs = {
|
|
268
|
+
telphone: { startCharIndex: -8, endCharIndex: -5 },
|
|
269
|
+
idcard: { startCharIndex: -12, endCharIndex: -5 }
|
|
270
|
+
};
|
|
271
|
+
/**
|
|
272
|
+
* 对给定的字符串进行脱敏处理
|
|
273
|
+
* @param data 需要处理的字符串
|
|
274
|
+
* @param options 配置参数对象
|
|
275
|
+
* @returns
|
|
276
|
+
*/
|
|
277
|
+
function maskData(data, options) {
|
|
278
|
+
if (typeof data !== 'string' || !data) {
|
|
279
|
+
return '';
|
|
280
|
+
}
|
|
281
|
+
const modeOpts = options && options.mode && modeIndexs[options.mode] ? modeIndexs[options.mode] : {};
|
|
282
|
+
const { maskWith, startCharIndex: start = 0, endCharIndex: end, startFrom, endUntil } = { maskWith: '*', ...modeOpts, ...options };
|
|
283
|
+
let handleData = data;
|
|
284
|
+
let beforeChars = '';
|
|
285
|
+
let afterChars = '';
|
|
286
|
+
const startFromIndex = startFrom ? data.indexOf(startFrom) : -1;
|
|
287
|
+
if (startFromIndex > -1) {
|
|
288
|
+
const index = startFromIndex + startFrom.length;
|
|
289
|
+
handleData = handleData.slice(index);
|
|
290
|
+
beforeChars = data.slice(0, index);
|
|
291
|
+
}
|
|
292
|
+
const endUtilIndex = endUntil ? data.lastIndexOf(endUntil) : -1;
|
|
293
|
+
if (endUtilIndex > -1) {
|
|
294
|
+
handleData = handleData.slice(0, endUtilIndex);
|
|
295
|
+
afterChars = data.slice(endUtilIndex);
|
|
296
|
+
}
|
|
297
|
+
const chars = handleData.split('');
|
|
298
|
+
const newChars = [beforeChars];
|
|
299
|
+
const charLen = chars.length;
|
|
300
|
+
const indexs = [start >= 0 ? start : charLen + start, end !== undefined ? (end >= 0 ? end : charLen + end) : charLen - 1];
|
|
301
|
+
let [startIdx, endIdx] = indexs;
|
|
302
|
+
endIdx = endIdx > 0 && endIdx < charLen ? endIdx : charLen - 1;
|
|
303
|
+
startIdx = startIdx >= 0 && startIdx <= endIdx ? startIdx : 0;
|
|
304
|
+
chars.forEach((char, idx) => {
|
|
305
|
+
newChars.push(idx >= startIdx && idx <= endIdx ? maskWith : char);
|
|
306
|
+
});
|
|
307
|
+
newChars.push(afterChars);
|
|
308
|
+
return newChars.join('');
|
|
309
|
+
}
|
|
310
|
+
|
|
256
311
|
const { hasOwnProperty, toString: toString$1 } = Object.prototype;
|
|
257
312
|
const objType = (val) => {
|
|
258
313
|
const typeKeys = toString$1.call(val).match(/^\[object (.*)\]$/);
|
|
@@ -477,7 +532,7 @@ const switchNullToUndefined = (data) => {
|
|
|
477
532
|
* 将搜素条件里的数组字段转换为其他格式,通常用于搜索表单的字段转换
|
|
478
533
|
* @param formData 传入参数
|
|
479
534
|
* @param maps 转换的映射关系,eg:{ date: ['startTime', 'endTime'] }
|
|
480
|
-
* @param
|
|
535
|
+
* @param options 额外的配置参数
|
|
481
536
|
*/
|
|
482
537
|
const formParamsSwitch = (formData, maps, options) => {
|
|
483
538
|
const dateKeys = Object.keys(maps);
|
|
@@ -499,10 +554,10 @@ const formParamsSwitch = (formData, maps, options) => {
|
|
|
499
554
|
const { filterNullable: filterNullableValue, dateFormat } = { filterNullable: true, ...options };
|
|
500
555
|
const handleData = accessKeys.reduce((acc, key) => {
|
|
501
556
|
const values = dateData[key];
|
|
502
|
-
|
|
557
|
+
const mapValue = maps[key];
|
|
558
|
+
if (!values || !mapValue) {
|
|
503
559
|
return acc;
|
|
504
560
|
}
|
|
505
|
-
const mapValue = maps[key];
|
|
506
561
|
// 数组合并操作/取最后一位操作
|
|
507
562
|
if (mapValue === 'join' || mapValue === 'pop') {
|
|
508
563
|
if (Array.isArray(values) && values.length) {
|
|
@@ -527,20 +582,188 @@ const formParamsSwitch = (formData, maps, options) => {
|
|
|
527
582
|
...handleData
|
|
528
583
|
};
|
|
529
584
|
return filterNullableValue ? filterNullable(result) : result;
|
|
530
|
-
};
|
|
585
|
+
};
|
|
586
|
+
/** 创建一个绑定了默认时间格式转换函数的formParamsSwitch函数 */
|
|
587
|
+
const formParamsSwitchCreator = (dateFormat) => (formData, maps, options) => formParamsSwitch(formData, maps, { dateFormat, ...options });
|
|
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
|
+
}
|
|
531
749
|
|
|
532
750
|
exports.ChinaIdCardValid = ChinaIdCardValid;
|
|
751
|
+
exports.NOMETHOD = NOMETHOD;
|
|
533
752
|
exports.array2tree = array2tree;
|
|
534
753
|
exports.awaitWrapper = awaitWrapper;
|
|
535
754
|
exports.byteParse = byteParse;
|
|
536
755
|
exports.byteStringify = byteStringify;
|
|
537
756
|
exports.checkoutBy = checkoutBy;
|
|
757
|
+
exports.eventTargetEmitter = eventTargetEmitter;
|
|
538
758
|
exports.filterNullable = filterNullable;
|
|
539
759
|
exports.formParamsSwitch = formParamsSwitch;
|
|
760
|
+
exports.formParamsSwitchCreator = formParamsSwitchCreator;
|
|
540
761
|
exports.formulaValidate = formulaValidate;
|
|
541
762
|
exports.isNullable = isNullable;
|
|
542
763
|
exports.mapToObject = mapToObject;
|
|
764
|
+
exports.maskData = maskData;
|
|
543
765
|
exports.objType = objType;
|
|
766
|
+
exports.pageCommunicate = pageCommunicate;
|
|
544
767
|
exports.pickRenameKeys = pickRenameKeys;
|
|
545
768
|
exports.safeJsonParse = safeJsonParse;
|
|
546
769
|
exports.switchNullToUndefined = switchNullToUndefined;
|
package/dist/index.min.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @wxhccc/es-util v1.
|
|
3
|
-
* (c)
|
|
2
|
+
* @wxhccc/es-util v1.7.0
|
|
3
|
+
* (c) 2022 wxhccc
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
6
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Smartfetch={})}(this,(function(e){"use strict";const{hasOwnProperty:t}=Object.prototype;function n(e,t=[]){return{[e]:t}}const r=/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i;const{hasOwnProperty:i,toString:c}=Object.prototype,o=e=>{const t=c.call(e).match(/^\[object (.*)\]$/);return t?t[1]:""};async function s(e){try{return[null,await e]}catch(e){return[e,void 0]}}const a={};function l(e,t){const n=function(e){return e?e._isVue||e.$&&e.$.vnode?"vue":"setState"in e?"react":"unknown":"unknown"}(this),r="unknown"!==n,c=r?this: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},_checkLockKey:{value:e=>a[e]},unlock:{value:K}}),g&&!O&&(x(!0),!b&&k.finally(K)),k}const u=Object.defineProperty(l,"_checkLockKey",{value:e=>a[e]}),f={install(e,t="$wp"){e.config&&"globalProperties"in e.config?e.config.globalProperties[t]=l:e.prototype[t]=l}};const p=(e,t)=>{const n={};return Object.keys(e).forEach((r=>{const i=e[r];""!==i&&null!=i&&(n[r]=t&&"[object Object]"===Object.prototype.toString.call(i)?p(i):i)})),n},{toString:y}=Object.prototype,b=e=>{if(null!==e)return Array.isArray(e)?e.map(b):("[object Object]"===y.call(e)&&Object.keys(e).forEach((t=>{e[t]=b(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=p,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?p(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=b,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=u,e.wpVuePlugin=f,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})}));
|
package/dist/object-array.d.ts
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
|
|
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:
|
|
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
|
|
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:
|
|
28
|
+
export declare function pickRenameKeys(object: AnyObject, keysMap: {
|
|
31
29
|
[key: string]: string;
|
|
32
|
-
}):
|
|
30
|
+
}): AnyObject | undefined;
|
|
33
31
|
export {};
|
package/dist/object-array.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @wxhccc/es-util v1.
|
|
3
|
-
* (c)
|
|
2
|
+
* @wxhccc/es-util v1.7.0
|
|
3
|
+
* (c) 2022 wxhccc
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
6
6
|
'use strict';
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
9
9
|
|
|
10
10
|
function mapToObject(objectArray, keyProp = 'key', valueProp = 'value') {
|
|
11
|
-
|
|
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
|
|
30
|
+
if (!isObject(object)) {
|
|
23
31
|
return [];
|
|
32
|
+
}
|
|
24
33
|
if (Array.isArray(keys)) {
|
|
25
|
-
return keys.map(item =>
|
|
34
|
+
return keys.map(item => object[item]);
|
|
26
35
|
}
|
|
27
|
-
else if (keys && keys
|
|
28
|
-
return Object.keys(keys).map(item => (object[item]
|
|
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
|
|
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]);
|
package/dist/optional.d.ts
CHANGED
|
@@ -32,14 +32,19 @@ export declare type ParamsSwitchMaps<DK extends string = string, RK extends stri
|
|
|
32
32
|
RK,
|
|
33
33
|
RK
|
|
34
34
|
] | [RK, RK, string] | 'join' | 'pop'>;
|
|
35
|
+
export declare type DateFormat = (date: any, format?: string) => string;
|
|
35
36
|
/**
|
|
36
37
|
* 将搜素条件里的数组字段转换为其他格式,通常用于搜索表单的字段转换
|
|
37
38
|
* @param formData 传入参数
|
|
38
39
|
* @param maps 转换的映射关系,eg:{ date: ['startTime', 'endTime'] }
|
|
39
|
-
* @param
|
|
40
|
+
* @param options 额外的配置参数
|
|
40
41
|
*/
|
|
41
|
-
export declare const formParamsSwitch: <
|
|
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
|
+
/** 是否需要过滤空数据 */
|
|
42
44
|
filterNullable?: boolean | undefined;
|
|
43
|
-
|
|
45
|
+
/** 时间格式换函数 */
|
|
46
|
+
dateFormat?: DateFormat | undefined;
|
|
44
47
|
} | undefined) => R;
|
|
48
|
+
/** 创建一个绑定了默认时间格式转换函数的formParamsSwitch函数 */
|
|
49
|
+
export declare const formParamsSwitchCreator: (dateFormat: DateFormat) => typeof formParamsSwitch;
|
|
45
50
|
export {};
|
|
@@ -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
package/dist/types.d.ts
ADDED
package/dist/validate.js
CHANGED