@wxhccc/es-util 1.7.0 → 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.
@@ -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,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,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.7.0
2
+ * @wxhccc/es-util v2.0.0
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;
@@ -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,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.7.0
2
+ * @wxhccc/es-util v2.0.0
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,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,9 +68,6 @@ 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
73
  const modeIndexs = {
@@ -81,7 +84,9 @@ function maskData(data, options) {
81
84
  if (typeof data !== 'string' || !data) {
82
85
  return '';
83
86
  }
84
- const modeOpts = options && options.mode && modeIndexs[options.mode] ? modeIndexs[options.mode] : {};
87
+ const modeOpts = options && options.mode && modeIndexs[options.mode]
88
+ ? modeIndexs[options.mode]
89
+ : {};
85
90
  const { maskWith, startCharIndex: start = 0, endCharIndex: end, startFrom, endUntil } = { maskWith: '*', ...modeOpts, ...options };
86
91
  let handleData = data;
87
92
  let beforeChars = '';
@@ -100,7 +105,10 @@ function maskData(data, options) {
100
105
  const chars = handleData.split('');
101
106
  const newChars = [beforeChars];
102
107
  const charLen = chars.length;
103
- const indexs = [start >= 0 ? start : charLen + start, end !== undefined ? (end >= 0 ? end : charLen + end) : charLen - 1];
108
+ const indexs = [
109
+ start >= 0 ? start : charLen + start,
110
+ end !== undefined ? (end >= 0 ? end : charLen + end) : charLen - 1
111
+ ];
104
112
  let [startIdx, endIdx] = indexs;
105
113
  endIdx = endIdx > 0 && endIdx < charLen ? endIdx : charLen - 1;
106
114
  startIdx = startIdx >= 0 && startIdx <= endIdx ? startIdx : 0;
@@ -111,6 +119,16 @@ function maskData(data, options) {
111
119
  return newChars.join('');
112
120
  }
113
121
 
114
- exports.byteParse = byteParse;
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;
115
133
  exports.byteStringify = byteStringify;
116
134
  exports.maskData = maskData;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wxhccc/es-util",
3
- "version": "1.7.0",
3
+ "version": "2.0.0",
4
4
  "description": "A library that contains some useful methods",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.esm.js",
@@ -10,7 +10,8 @@
10
10
  "start": "npm run dev",
11
11
  "test": "jest",
12
12
  "dev": "rollup -w -c --environment NODE_ENV:development",
13
- "build": "rollup -c"
13
+ "clean": "rimraf dist/**",
14
+ "build": "yarn clean && rollup -c"
14
15
  },
15
16
  "keywords": [
16
17
  "array-tree-switch",
@@ -42,23 +43,23 @@
42
43
  "@rollup/plugin-commonjs": "^18.0.0",
43
44
  "@rollup/plugin-node-resolve": "^11.2.1",
44
45
  "@types/jest": "^26.0.23",
45
- "@typescript-eslint/eslint-plugin": "^2.19.0",
46
- "@typescript-eslint/parser": "^2.19.0",
47
- "@vue/test-utils": "^2.0.0-rc.6",
46
+ "@types/lodash": "^4.14.182",
47
+ "@typescript-eslint/eslint-plugin": "^5.30.7",
48
+ "@typescript-eslint/parser": "^5.30.7",
48
49
  "babel-eslint": "^8.2.6",
49
- "enzyme": "^3.11.0",
50
- "enzyme-adapter-react-16": "^1.15.6",
51
- "eslint": "^4.19.1",
52
- "jest": "^26.6.3",
53
- "lodash": "^4.17.15",
54
- "react": "^17.0.2",
55
- "react-dom": "^17.0.2",
56
- "rollup": "^2.45.1",
50
+ "eslint": "^8.20.0",
51
+ "eslint-config-prettier": "^8.5.0",
52
+ "eslint-plugin-prettier": "^4.2.1",
53
+ "jest": "^28.1.3",
54
+ "jest-environment-jsdom": "^28.1.3",
55
+ "prettier": "^2.7.1",
56
+ "rimraf": "^3.0.2",
57
+ "rollup": "^2.77.0",
57
58
  "rollup-plugin-terser": "^7.0.2",
58
- "rollup-plugin-typescript2": "^0.30.0",
59
+ "rollup-plugin-typescript2": "^0.32.1",
60
+ "ts-jest": "^28.0.7",
59
61
  "tslib": "^1.10.0",
60
- "typescript": "^4.2.4",
61
- "vue": "^3.0.11"
62
+ "typescript": "^4.7.4"
62
63
  },
63
64
  "files": [
64
65
  "dist"