@wxhccc/es-util 1.5.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/promise.js CHANGED
@@ -1,17 +1,14 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.5.2
3
- * (c) 2021 wxhccc
2
+ * @wxhccc/es-util v2.0.0
3
+ * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
7
7
 
8
8
  Object.defineProperty(exports, '__esModule', { value: true });
9
9
 
10
- const { hasOwnProperty, toString } = Object.prototype;
11
- const objType = (val) => {
12
- const typeKeys = toString.call(val).match(/^\[object (.*)\]$/);
13
- return typeKeys ? typeKeys[1] : '';
14
- };
10
+ var utils = require('./utils.js');
11
+
15
12
  /**
16
13
  * wrap promise and handle reject or err by return an array like [error, undefined]
17
14
  * @param promise promise
@@ -26,160 +23,55 @@ async function awaitWrapper(promise) {
26
23
  return [err, undefined];
27
24
  }
28
25
  }
29
- function checkContext(context) {
30
- if (!context)
31
- return 'unknown';
32
- if (context._isVue || (context.$ && context.$.vnode)) {
33
- return 'vue';
34
- }
35
- else if ('setState' in context) {
36
- return 'react';
37
- }
38
- return 'unknown';
39
- }
40
- const emptyPromise = () => {
41
- const ep = Promise.resolve(undefined);
42
- return Object.assign(ep, {
43
- then(...args) {
44
- const [onfulfilled] = args;
45
- // if then has be called by Promise.all, let ite pass
46
- if (args.length === 2 && typeof onfulfilled === 'function') {
47
- return onfulfilled(undefined);
48
- }
49
- return ep;
50
- },
51
- catch: (onrejected) => ep,
52
- finally: () => ep
53
- });
54
- };
55
- const lockCtx = {};
56
- function wrapPromise(promise, wrapOrOptions) {
57
- const contextType = checkContext(this);
58
- const isReactiveIns = contextType !== 'unknown';
59
- const context = isReactiveIns ? this : lockCtx;
60
- const stateKey = contextType === 'react' ? 'state' : '';
61
- const contextState = stateKey ? context[stateKey] : context;
62
- const { wrap, lock, syncRefHandle, manualUnlock } = typeof wrapOrOptions === 'boolean' ? { wrap: wrapOrOptions } : { ...wrapOrOptions };
26
+ function wrapPromise(promise, options) {
27
+ const { wrap, lock, syncRefHandle } = { ...options };
63
28
  let lockSwitchHook = undefined;
64
29
  let lockRefHandle = undefined;
65
- let lockKey = [];
66
30
  let needLock = false;
67
- let ignoreLock = false;
68
- const has = (val, key) => !!val && hasOwnProperty.call(val, key);
69
- const isObj = (obj) => objType(obj) === 'Object';
70
- const getValue = (obj, path) => {
71
- let result = false;
72
- if (obj && isObj(obj) && Array.isArray(path) && path.length) {
73
- let curObj = obj;
74
- for (let i = 0; i < path.length; i++) {
75
- const key = path[i];
76
- if (typeof curObj !== 'object' || !has(curObj, key)) {
77
- break;
78
- }
79
- curObj = curObj[key];
80
- i === path.length - 1 &&
81
- (result = (typeof curObj === 'boolean') ? curObj : false);
82
- }
83
- }
84
- return result;
85
- };
86
- const setValue = (obj, path, value) => {
87
- // if vue2 and path[0] not defined, do nothing
88
- if (contextType === 'vue' && context.$set && !has(obj, path[0]))
89
- return;
90
- const { $set = (o, key, val) => { o[key] = val; } } = context;
91
- const isStateRect = contextType === 'react';
92
- const originObj = isStateRect ? { ...obj } : obj;
93
- let curObj = originObj;
94
- let canSet = false;
95
- for (let i = 0; i < path.length; i++) {
96
- const key = path[i];
97
- const keyExist = has(curObj, key);
98
- if (i === path.length - 1) {
99
- const isBool = typeof curObj[key] === 'boolean';
100
- canSet = !keyExist || isBool;
101
- canSet && $set(curObj, key, value);
102
- }
103
- else {
104
- !keyExist && $set(curObj, key, {});
105
- if (!isObj(curObj[key]))
106
- break;
107
- isStateRect && (curObj[key] = { ...curObj[key] });
108
- curObj = curObj[key];
109
- }
110
- }
111
- // trigger setState when run in react class component
112
- isStateRect && canSet && context.setState({ [path[0]]: originObj[path[0]] });
113
- };
31
+ let isLocking = false;
114
32
  const stateLock = (bool) => {
115
- if (lockKey.length) {
116
- // if not reactive instance, save lock key as string, no need to structure nested object
117
- isReactiveIns ? setValue(contextState, lockKey, bool) : (lockCtx[lock] = bool);
118
- return;
119
- }
120
- if (lockRefHandle)
33
+ if (lockRefHandle) {
121
34
  lockRefHandle[0][lockRefHandle[1]] = bool;
122
- if (lockSwitchHook)
35
+ }
36
+ if (lockSwitchHook) {
123
37
  lockSwitchHook(bool);
38
+ }
124
39
  };
125
40
  const checkLock = () => {
126
- // use refHandle if contextState not update sync
127
- if (lockRefHandle)
128
- return lockRefHandle[0][lockRefHandle[1]];
129
- if (!isReactiveIns && typeof lock === 'string')
130
- return contextState[lock];
131
- return getValue(contextState, lockKey);
41
+ // use refHandle if state not update sync
42
+ return lockRefHandle ? lockRefHandle[0][lockRefHandle[1]] : false;
132
43
  };
133
44
  if (lock) {
134
- const isRefHandle = (val) => Array.isArray(val) && val.length === 2;
135
- if (typeof lock === 'string') {
136
- lockKey = lock.split('.');
137
- }
138
- else if (isRefHandle(lock)) {
45
+ const isRefHandle = (val) => utils.isArr(val) && val.length === 2;
46
+ if (isRefHandle(lock)) {
139
47
  lockRefHandle = lock;
140
48
  }
141
- else if (typeof lock === 'function') {
49
+ else if (utils.isFn(lock)) {
142
50
  lockSwitchHook = lock;
143
51
  if (isRefHandle(syncRefHandle)) {
144
52
  lockRefHandle = syncRefHandle;
145
53
  }
146
54
  }
147
- needLock = lockKey.length > 0 || !!lockRefHandle || !!lockSwitchHook;
148
- needLock && (ignoreLock = checkLock());
55
+ needLock = !!(lockSwitchHook || lockRefHandle);
56
+ needLock && (isLocking = checkLock());
149
57
  }
150
58
  let corePromsie;
151
59
  // if promise is a function, here need to call it in promise.then to use locking check to prevent next call
152
- if (typeof promise === 'function') {
153
- corePromsie = ignoreLock ? emptyPromise() : wrap ? awaitWrapper(promise()) : promise();
60
+ if (utils.isFn(promise)) {
61
+ const truePromise = isLocking ? Promise.resolve(undefined) : promise();
62
+ corePromsie = wrap ? awaitWrapper(truePromise) : truePromise;
154
63
  }
155
64
  else {
156
65
  corePromsie = wrap ? awaitWrapper(promise) : promise;
157
66
  }
158
- const unlock = () => stateLock(false);
159
- Object.defineProperties(corePromsie, {
160
- '__lockValue': { get: checkLock },
161
- _checkLockKey: { value: (key) => lockCtx[key] },
162
- unlock: { value: unlock }
163
- });
164
- if (needLock && !ignoreLock) {
67
+ if (corePromsie instanceof Promise && needLock && !isLocking) {
165
68
  stateLock(true);
166
- !manualUnlock && corePromsie.finally(unlock);
69
+ corePromsie.finally(() => stateLock(false));
167
70
  }
168
71
  return corePromsie;
169
72
  }
170
- const wp = Object.defineProperty(wrapPromise, '_checkLockKey', { value: (key) => lockCtx[key] });
171
- const wpVuePlugin = {
172
- install(appOrVue, key = '$wp') {
173
- if (appOrVue.config && 'globalProperties' in appOrVue.config) {
174
- appOrVue.config.globalProperties[key] = wrapPromise;
175
- }
176
- else {
177
- appOrVue.prototype[key] = wrapPromise;
178
- }
179
- }
180
- };
73
+ /** short for method `wrapPromise` */
74
+ const wp = wrapPromise;
181
75
 
182
76
  exports.awaitWrapper = awaitWrapper;
183
- exports.objType = objType;
184
77
  exports.wp = wp;
185
- exports.wpVuePlugin = wpVuePlugin;
@@ -0,0 +1,36 @@
1
+ interface TaskItem {
2
+ /** 定时器回调函数 */
3
+ callback: (ts: number) => void;
4
+ /** 定时器运行间隔 */
5
+ interval: number;
6
+ /** 距离上次执行的时间 */
7
+ elapsed: number;
8
+ /** 最大运行次数 */
9
+ maxTime?: number;
10
+ /** 已运行次数 */
11
+ runTime: number;
12
+ /** 当前任务是否需要在下个循环周期时清除,内部变量 */
13
+ needClear?: boolean;
14
+ }
15
+ export declare type TimerCallback = TaskItem['callback'];
16
+ export interface RAFTimerOptions {
17
+ /** 无任务时是否自动停止,停止后需要手动启动 */
18
+ autoStopWhenNoTask?: boolean;
19
+ /** 添加任务时自动启动,可以配合autoStopWhenNoTask使用 */
20
+ autoStartWhenAddTask?: boolean;
21
+ }
22
+ /**
23
+ * 创建一个计时器
24
+ * @returns
25
+ */
26
+ export declare const createRAFTimer: (options?: RAFTimerOptions) => {
27
+ start: () => void;
28
+ stop: () => void;
29
+ pauseToggle: () => void;
30
+ addTask: (callback: TaskItem['callback'], interval: number, maxTime?: number) => void;
31
+ removeTask: (callback: TaskItem['callback']) => void;
32
+ isPaused: () => boolean;
33
+ };
34
+ /** 计时器实例 */
35
+ export declare type TimerInstance = ReturnType<typeof createRAFTimer>;
36
+ export {};
@@ -0,0 +1,103 @@
1
+ /*!
2
+ * @wxhccc/es-util v2.0.0
3
+ * (c) 2022 wxhccc
4
+ * @license MIT
5
+ */
6
+ 'use strict';
7
+
8
+ Object.defineProperty(exports, '__esModule', { value: true });
9
+
10
+ /**
11
+ * 创建一个计时器
12
+ * @returns
13
+ */
14
+ const createRAFTimer = (options) => {
15
+ const { autoStopWhenNoTask, autoStartWhenAddTask } = { ...options };
16
+ // 计时器句柄
17
+ let ticker = 0;
18
+ // 是否暂停状态
19
+ let paused = true;
20
+ // 计时器实际运行时间,不包括暂停区间
21
+ let timeStamp = 0;
22
+ // 上一次时序记录的时间戳
23
+ let lastTimeStamp = 0;
24
+ let tasks = [];
25
+ let taskNeedClear = false;
26
+ const timerHandler = (time) => {
27
+ const delta = time - (lastTimeStamp || time);
28
+ lastTimeStamp = time;
29
+ timeStamp += delta;
30
+ if (taskNeedClear) {
31
+ tasks = tasks.filter((item) => !item.needClear);
32
+ taskNeedClear = false;
33
+ }
34
+ // will auto stop when autoStopWhenNoTask is true and no task
35
+ if (autoStopWhenNoTask && !tasks.length) {
36
+ paused = true;
37
+ return;
38
+ }
39
+ tasks.forEach((item) => {
40
+ const { callback, maxTime, runTime, elapsed, interval, needClear } = item;
41
+ if (needClear) {
42
+ return;
43
+ }
44
+ if (maxTime && runTime >= maxTime) {
45
+ item.needClear = true;
46
+ taskNeedClear = true;
47
+ return;
48
+ }
49
+ if (elapsed >= interval) {
50
+ try {
51
+ callback(timeStamp);
52
+ }
53
+ catch (e) { }
54
+ item.elapsed = 0;
55
+ item.runTime += 1;
56
+ }
57
+ else {
58
+ item.elapsed += delta;
59
+ }
60
+ });
61
+ ticker = window.requestAnimationFrame(timerHandler);
62
+ };
63
+ /** start timer(开始计时器) */
64
+ const start = () => {
65
+ ticker = window.requestAnimationFrame(timerHandler);
66
+ paused = false;
67
+ };
68
+ /** stop timer(停止计时器) */
69
+ const stop = () => {
70
+ window.cancelAnimationFrame(ticker);
71
+ paused = true;
72
+ };
73
+ /** start/stop toggle (开启和停止切换) */
74
+ const pauseToggle = () => {
75
+ paused ? start() : stop();
76
+ };
77
+ const isPaused = () => paused;
78
+ /**
79
+ * add new task (添加定时任务,注意:无引用关系函数无法被remove,如需提前移除,需要确保函数可被寻到)
80
+ * @param callback task callback (任务回调函数)
81
+ * @param interval callback trigger interval, unit: ms (回调触发间隔,单位:ms)
82
+ * @param maxTime max time callback trigger (回调函数的最大触发次数)
83
+ */
84
+ const addTask = (callback, interval, maxTime) => {
85
+ if (!callback) {
86
+ return;
87
+ }
88
+ if (autoStartWhenAddTask && paused) {
89
+ start();
90
+ }
91
+ tasks.push({ callback, elapsed: 0, interval, maxTime, runTime: 0 });
92
+ };
93
+ /**
94
+ * remove task (移除定时任务)
95
+ * @param callback task callback (任务回调函数)
96
+ */
97
+ const removeTask = (callback) => {
98
+ tasks = tasks.filter((item) => item.callback !== callback);
99
+ };
100
+ return { start, stop, pauseToggle, addTask, removeTask, isPaused };
101
+ };
102
+
103
+ exports.createRAFTimer = createRAFTimer;
@@ -0,0 +1,4 @@
1
+ export declare type AnyObject = {
2
+ [key: string]: any;
3
+ };
4
+ export declare type AnyFunction<T = any> = (...args: any[]) => T;
@@ -0,0 +1,10 @@
1
+ import { AnyFunction, AnyObject } from './types';
2
+ export declare const objForEch: <T extends {
3
+ [key: string]: any;
4
+ }, K extends string = Extract<keyof T, "string">>(obj: T, callbackfn: (key: K, value: T[K], index: number) => void) => void;
5
+ export declare const isFn: (fn: unknown) => fn is AnyFunction<any>;
6
+ export declare const isArr: (arg: any) => arg is any[];
7
+ export declare const objToString: (obj: unknown) => string;
8
+ export declare const objType: (val: unknown) => string;
9
+ export declare const isObj: (obj: unknown) => obj is AnyObject;
10
+ export declare const hasOwnProp: (obj: AnyObject, v: PropertyKey) => boolean;
package/dist/utils.js ADDED
@@ -0,0 +1,30 @@
1
+ /*!
2
+ * @wxhccc/es-util v2.0.0
3
+ * (c) 2022 wxhccc
4
+ * @license MIT
5
+ */
6
+ 'use strict';
7
+
8
+ Object.defineProperty(exports, '__esModule', { value: true });
9
+
10
+ const { hasOwnProperty, toString } = Object.prototype;
11
+ const objForEch = (obj, callbackfn) => {
12
+ Object.keys(obj).forEach((key, index) => callbackfn(key, obj[key], index));
13
+ };
14
+ const isFn = (fn) => typeof fn === 'function';
15
+ const isArr = Array.isArray;
16
+ const objToString = (obj) => toString.call(obj);
17
+ const objType = (val) => {
18
+ const typeKeys = objToString(val).match(/^\[object (.*)\]$/);
19
+ return typeKeys ? typeKeys[1] : '';
20
+ };
21
+ const isObj = (obj) => objType(obj) === 'Object';
22
+ const hasOwnProp = (obj, v) => hasOwnProperty.call(obj, v);
23
+
24
+ exports.hasOwnProp = hasOwnProp;
25
+ exports.isArr = isArr;
26
+ exports.isFn = isFn;
27
+ exports.isObj = isObj;
28
+ exports.objForEch = objForEch;
29
+ exports.objToString = objToString;
30
+ exports.objType = objType;
package/dist/validate.js CHANGED
@@ -1,18 +1,56 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.5.2
3
- * (c) 2021 wxhccc
2
+ * @wxhccc/es-util v2.0.0
3
+ * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
7
7
 
8
8
  Object.defineProperty(exports, '__esModule', { value: true });
9
9
 
10
+ var utils = require('./utils.js');
11
+
10
12
  /* 身份证正则 */
11
13
  const idCardReg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i;
12
14
  /* 身份证合法性验证 */
13
15
  function ChinaIdCardValid(idNo) {
14
16
  const idNumber = idNo.toString().toUpperCase();
15
- const provCodes = ['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'];
17
+ const provCodes = [
18
+ '11',
19
+ '12',
20
+ '13',
21
+ '14',
22
+ '15',
23
+ '21',
24
+ '22',
25
+ '23',
26
+ '31',
27
+ '32',
28
+ '33',
29
+ '34',
30
+ '35',
31
+ '36',
32
+ '37',
33
+ '41',
34
+ '42',
35
+ '43',
36
+ '44',
37
+ '45',
38
+ '46',
39
+ '50',
40
+ '51',
41
+ '52',
42
+ '53',
43
+ '54',
44
+ '61',
45
+ '62',
46
+ '63',
47
+ '64',
48
+ '65',
49
+ '71',
50
+ '81',
51
+ '82',
52
+ '91'
53
+ ];
16
54
  const lastCodeCheck = () => {
17
55
  if (idNumber.length === 18) {
18
56
  const chars = idNumber.split('');
@@ -34,7 +72,9 @@ function ChinaIdCardValid(idNo) {
34
72
  }
35
73
  return true;
36
74
  };
37
- return idCardReg.test(idNumber) && provCodes.includes(idNumber.substr(0, 2)) && lastCodeCheck();
75
+ return (idCardReg.test(idNumber) &&
76
+ provCodes.includes(idNumber.substr(0, 2)) &&
77
+ lastCodeCheck());
38
78
  }
39
79
  // 公式验证函数
40
80
  function formulaValidate(string, variables) {
@@ -46,7 +86,8 @@ function formulaValidate(string, variables) {
46
86
  const bns = /[^+\-*/]\(/; // 错误情况,(前面不是运算符
47
87
  const blns = /\)[^+\-*/]/; // 错误情况,)后面不是运算符
48
88
  const bmatch = () => {
49
- let stack = [];
89
+ // 错误情况,括号不配对
90
+ const stack = [];
50
91
  for (let i = 0, item; i < string.length; i++) {
51
92
  item = string.charAt(i);
52
93
  if (item === '(') {
@@ -67,9 +108,16 @@ function formulaValidate(string, variables) {
67
108
  const varInList = (vars) => {
68
109
  const tmpStr = string.replace(/[()+\-*/]{1,}/g, '`');
69
110
  const array = tmpStr.split('`');
70
- return array.every(item => (!/[A-Z]/i.test(item) || vars.includes(item)));
111
+ return array.every((item) => !/[A-Z]/i.test(item) || vars.includes(item));
71
112
  };
72
- return !sc.test(string) && !eb.test(string) && !sl.test(string) && !bs.test(string) && !bns.test(string) && !blns.test(string) && bmatch() && (!Array.isArray(variables) || varInList(variables));
113
+ return (!sc.test(string) &&
114
+ !eb.test(string) &&
115
+ !sl.test(string) &&
116
+ !bs.test(string) &&
117
+ !bns.test(string) &&
118
+ !blns.test(string) &&
119
+ bmatch() &&
120
+ (!utils.isArr(variables) || varInList(variables)));
73
121
  }
74
122
 
75
123
  exports.ChinaIdCardValid = ChinaIdCardValid;
@@ -8,5 +8,4 @@ export declare function byteStringify(byteNum: number | string, options?: Option
8
8
  value: string | number;
9
9
  unit: string;
10
10
  } | undefined;
11
- export declare function byteParse(byteStr: string, options?: {}): void;
12
11
  export {};
@@ -1 +1,3 @@
1
1
  export * from './byte-string';
2
+ export * from './mask-data';
3
+ export * from './uri-b64';
@@ -0,0 +1,21 @@
1
+ export 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;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * 将字符串编码为base64, 采用encodeURIComponent+window.btoa,主要为了解决atob/btoa处理特殊字符会报错的问题,性能不如buffer方案,适用于简单场景
3
+ * @param str 待转换的字符串
4
+ * @returns
5
+ */
6
+ export declare const b64UriEncode: (str: string) => string;
7
+ /** b64UriEncode对应的解码函数 */
8
+ export declare const b64UriDecode: (str: string) => string;
@@ -1,12 +1,14 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.5.2
3
- * (c) 2021 wxhccc
2
+ * @wxhccc/es-util v2.0.0
3
+ * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
6
6
  'use strict';
7
7
 
8
8
  Object.defineProperty(exports, '__esModule', { value: true });
9
9
 
10
+ var utils = require('./utils.js');
11
+
10
12
  //
11
13
  const configCreater = (standard, unit) => {
12
14
  const unitMap = {
@@ -20,7 +22,11 @@ const configCreater = (standard, unit) => {
20
22
  Z: { expMax: 7, units: { metric: 'ZB', iec: 'ZiB', jedec: 'ZB' } },
21
23
  Y: { expMax: 8, units: { metric: 'YB', iec: 'YiB', jedec: 'YB' } }
22
24
  };
23
- const standBase = { metric: 1000, iec: 1024, jedec: 1024 };
25
+ const standBase = {
26
+ metric: 1000,
27
+ iec: 1024,
28
+ jedec: 1024
29
+ };
24
30
  return {
25
31
  base: standBase[standard] || standBase['jedec'],
26
32
  unitMap: unitMap[unit] || Object.values(unitMap)
@@ -44,14 +50,14 @@ function byteStringify(byteNum, options) {
44
50
  const getValue = (value) => Number.isInteger(value) ? value : value.toFixed(precision);
45
51
  let resUnit = '';
46
52
  let resValue = 0;
47
- if (!Array.isArray(unitMap)) {
53
+ if (!utils.isArr(unitMap)) {
48
54
  const maxValue = Math.pow(base, unitMap.expMax);
49
55
  resUnit = unitMap.units[standard];
50
56
  const value = byteNumber / maxValue;
51
57
  resValue = getValue(value * negative);
52
58
  }
53
59
  else {
54
- unitMap.some(item => {
60
+ unitMap.some((item) => {
55
61
  const maxValue = Math.pow(base, item.expMax);
56
62
  const value = byteNumber / maxValue;
57
63
  if (value > base)
@@ -62,10 +68,67 @@ function byteStringify(byteNum, options) {
62
68
  });
63
69
  }
64
70
  return detail ? { value: resValue, unit: resUnit } : `${resValue} ${resUnit}`;
65
- }
66
- // translate string to byte num
67
- function byteParse(byteStr, options = {}) {
68
71
  }
69
72
 
70
- exports.byteParse = byteParse;
73
+ const modeIndexs = {
74
+ telphone: { startCharIndex: -8, endCharIndex: -5 },
75
+ idcard: { startCharIndex: -12, endCharIndex: -5 }
76
+ };
77
+ /**
78
+ * 对给定的字符串进行脱敏处理
79
+ * @param data 需要处理的字符串
80
+ * @param options 配置参数对象
81
+ * @returns
82
+ */
83
+ function maskData(data, options) {
84
+ if (typeof data !== 'string' || !data) {
85
+ return '';
86
+ }
87
+ const modeOpts = options && options.mode && modeIndexs[options.mode]
88
+ ? modeIndexs[options.mode]
89
+ : {};
90
+ const { maskWith, startCharIndex: start = 0, endCharIndex: end, startFrom, endUntil } = { maskWith: '*', ...modeOpts, ...options };
91
+ let handleData = data;
92
+ let beforeChars = '';
93
+ let afterChars = '';
94
+ const startFromIndex = startFrom ? data.indexOf(startFrom) : -1;
95
+ if (startFromIndex > -1) {
96
+ const index = startFromIndex + startFrom.length;
97
+ handleData = handleData.slice(index);
98
+ beforeChars = data.slice(0, index);
99
+ }
100
+ const endUtilIndex = endUntil ? data.lastIndexOf(endUntil) : -1;
101
+ if (endUtilIndex > -1) {
102
+ handleData = handleData.slice(0, endUtilIndex);
103
+ afterChars = data.slice(endUtilIndex);
104
+ }
105
+ const chars = handleData.split('');
106
+ const newChars = [beforeChars];
107
+ const charLen = chars.length;
108
+ const indexs = [
109
+ start >= 0 ? start : charLen + start,
110
+ end !== undefined ? (end >= 0 ? end : charLen + end) : charLen - 1
111
+ ];
112
+ let [startIdx, endIdx] = indexs;
113
+ endIdx = endIdx > 0 && endIdx < charLen ? endIdx : charLen - 1;
114
+ startIdx = startIdx >= 0 && startIdx <= endIdx ? startIdx : 0;
115
+ chars.forEach((char, idx) => {
116
+ newChars.push(idx >= startIdx && idx <= endIdx ? maskWith : char);
117
+ });
118
+ newChars.push(afterChars);
119
+ return newChars.join('');
120
+ }
121
+
122
+ /**
123
+ * 将字符串编码为base64, 采用encodeURIComponent+window.btoa,主要为了解决atob/btoa处理特殊字符会报错的问题,性能不如buffer方案,适用于简单场景
124
+ * @param str 待转换的字符串
125
+ * @returns
126
+ */
127
+ const b64UriEncode = (str) => window.btoa(encodeURIComponent(str));
128
+ /** b64UriEncode对应的解码函数 */
129
+ const b64UriDecode = (str) => decodeURIComponent(window.atob(str));
130
+
131
+ exports.b64UriDecode = b64UriDecode;
132
+ exports.b64UriEncode = b64UriEncode;
71
133
  exports.byteStringify = byteStringify;
134
+ exports.maskData = maskData;