@wxhccc/es-util 1.6.0 → 2.0.1

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.
Files changed (39) hide show
  1. package/LICENSE +20 -20
  2. package/README.md +286 -57
  3. package/dist/array-tree-switch.d.ts +18 -2
  4. package/dist/date-time.d.ts +14 -0
  5. package/dist/event-target-emitter.d.ts +45 -0
  6. package/dist/event-target-emitter.js +147 -0
  7. package/dist/index.d.ts +4 -0
  8. package/dist/index.esm.js +499 -216
  9. package/dist/index.js +505 -218
  10. package/dist/index.min.js +2 -2
  11. package/dist/object-array.d.ts +7 -9
  12. package/dist/object-array.js +34 -16
  13. package/dist/optional.d.ts +6 -9
  14. package/dist/optional.js +136 -0
  15. package/dist/page-communicate.d.ts +27 -0
  16. package/dist/page-communicate.js +66 -0
  17. package/dist/promise.d.ts +21 -24
  18. package/dist/promise.js +24 -132
  19. package/dist/raf-timer.d.ts +36 -0
  20. package/dist/raf-timer.js +103 -0
  21. package/dist/types.d.ts +4 -0
  22. package/dist/utils.d.ts +10 -0
  23. package/dist/utils.js +30 -0
  24. package/dist/validate.js +54 -6
  25. package/dist/value-string-switch/byte-string.d.ts +9 -4
  26. package/dist/value-string-switch/index.d.ts +1 -0
  27. package/dist/value-string-switch/mask-data.d.ts +1 -2
  28. package/dist/value-string-switch/uri-b64.d.ts +8 -0
  29. package/dist/value-string-switch.js +28 -11
  30. package/package.json +19 -19
  31. package/types/array-tree-switch.d.ts +0 -49
  32. package/types/index.d.ts +0 -6
  33. package/types/object-array.d.ts +0 -33
  34. package/types/optional.d.ts +0 -50
  35. package/types/promise.d.ts +0 -44
  36. package/types/validate.d.ts +0 -2
  37. package/types/value-string-switch/byte-string.d.ts +0 -12
  38. package/types/value-string-switch/index.d.ts +0 -2
  39. package/types/value-string-switch/mask-data.d.ts +0 -22
package/dist/promise.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.6.0
2
+ * @wxhccc/es-util v2.0.1
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -7,11 +7,8 @@
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.1
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.1
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,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.6.0
2
+ * @wxhccc/es-util v2.0.1
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -7,12 +7,50 @@
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;
@@ -4,9 +4,14 @@ interface Options {
4
4
  precision?: number;
5
5
  detail?: boolean;
6
6
  }
7
- export declare function byteStringify(byteNum: number | string, options?: Options): string | {
8
- value: string | number;
7
+ declare type StrOrNum = number | string;
8
+ export declare function byteStringify(byteNum: StrOrNum, options?: Options & {
9
+ detail?: false;
10
+ }): string;
11
+ export declare function byteStringify(byteNum: StrOrNum, options: Options & {
12
+ detail: true;
13
+ }): {
14
+ value: StrOrNum;
9
15
  unit: string;
10
- } | undefined;
11
- export declare function byteParse(byteStr: string, options?: {}): void;
16
+ };
12
17
  export {};
@@ -1,2 +1,3 @@
1
1
  export * from './byte-string';
2
2
  export * from './mask-data';
3
+ export * from './uri-b64';
@@ -1,4 +1,4 @@
1
- interface MaskDataOptions {
1
+ export interface MaskDataOptions {
2
2
  /** 替换的字符,默认为* */
3
3
  maskWith?: string;
4
4
  /** 起始字符索引,为负数时从字符串结尾起倒数第几个数开始 */
@@ -19,4 +19,3 @@ interface MaskDataOptions {
19
19
  * @returns
20
20
  */
21
21
  export declare function maskData(data: string, options?: MaskDataOptions): string;
22
- export {};
@@ -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,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.6.0
2
+ * @wxhccc/es-util v2.0.1
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -7,6 +7,8 @@
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,13 +22,16 @@ 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)
27
33
  };
28
34
  };
29
- // translate byte num to string
30
35
  function byteStringify(byteNum, options) {
31
36
  const opts = Object.assign({
32
37
  standard: 'jedec',
@@ -44,14 +49,14 @@ function byteStringify(byteNum, options) {
44
49
  const getValue = (value) => Number.isInteger(value) ? value : value.toFixed(precision);
45
50
  let resUnit = '';
46
51
  let resValue = 0;
47
- if (!Array.isArray(unitMap)) {
52
+ if (!utils.isArr(unitMap)) {
48
53
  const maxValue = Math.pow(base, unitMap.expMax);
49
54
  resUnit = unitMap.units[standard];
50
55
  const value = byteNumber / maxValue;
51
56
  resValue = getValue(value * negative);
52
57
  }
53
58
  else {
54
- unitMap.some(item => {
59
+ unitMap.some((item) => {
55
60
  const maxValue = Math.pow(base, item.expMax);
56
61
  const value = byteNumber / maxValue;
57
62
  if (value > base)
@@ -62,9 +67,6 @@ function byteStringify(byteNum, options) {
62
67
  });
63
68
  }
64
69
  return detail ? { value: resValue, unit: resUnit } : `${resValue} ${resUnit}`;
65
- }
66
- // translate string to byte num
67
- function byteParse(byteStr, options = {}) {
68
70
  }
69
71
 
70
72
  const modeIndexs = {
@@ -81,7 +83,9 @@ function maskData(data, options) {
81
83
  if (typeof data !== 'string' || !data) {
82
84
  return '';
83
85
  }
84
- const modeOpts = options && options.mode && modeIndexs[options.mode] ? modeIndexs[options.mode] : {};
86
+ const modeOpts = options && options.mode && modeIndexs[options.mode]
87
+ ? modeIndexs[options.mode]
88
+ : {};
85
89
  const { maskWith, startCharIndex: start = 0, endCharIndex: end, startFrom, endUntil } = { maskWith: '*', ...modeOpts, ...options };
86
90
  let handleData = data;
87
91
  let beforeChars = '';
@@ -100,7 +104,10 @@ function maskData(data, options) {
100
104
  const chars = handleData.split('');
101
105
  const newChars = [beforeChars];
102
106
  const charLen = chars.length;
103
- const indexs = [start >= 0 ? start : charLen + start, end !== undefined ? (end >= 0 ? end : charLen + end) : charLen - 1];
107
+ const indexs = [
108
+ start >= 0 ? start : charLen + start,
109
+ end !== undefined ? (end >= 0 ? end : charLen + end) : charLen - 1
110
+ ];
104
111
  let [startIdx, endIdx] = indexs;
105
112
  endIdx = endIdx > 0 && endIdx < charLen ? endIdx : charLen - 1;
106
113
  startIdx = startIdx >= 0 && startIdx <= endIdx ? startIdx : 0;
@@ -111,6 +118,16 @@ function maskData(data, options) {
111
118
  return newChars.join('');
112
119
  }
113
120
 
114
- exports.byteParse = byteParse;
121
+ /**
122
+ * 将字符串编码为base64, 采用encodeURIComponent+window.btoa,主要为了解决atob/btoa处理特殊字符会报错的问题,性能不如buffer方案,适用于简单场景
123
+ * @param str 待转换的字符串
124
+ * @returns
125
+ */
126
+ const b64UriEncode = (str) => window.btoa(encodeURIComponent(str));
127
+ /** b64UriEncode对应的解码函数 */
128
+ const b64UriDecode = (str) => decodeURIComponent(window.atob(str));
129
+
130
+ exports.b64UriDecode = b64UriDecode;
131
+ exports.b64UriEncode = b64UriEncode;
115
132
  exports.byteStringify = byteStringify;
116
133
  exports.maskData = maskData;