@mudbean/utils 2.0.5

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 (58) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/LICENSE +15 -0
  3. package/README.md +51 -0
  4. package/cjs/array/difference.js +48 -0
  5. package/cjs/array/index.js +133 -0
  6. package/cjs/array/intersection.js +40 -0
  7. package/cjs/array/symmetricDifference.js +45 -0
  8. package/cjs/array/union.js +62 -0
  9. package/cjs/className.js +55 -0
  10. package/cjs/createBezier.js +135 -0
  11. package/cjs/getRandomNumber.js +70 -0
  12. package/cjs/getRandomString.js +143 -0
  13. package/cjs/index.js +40 -0
  14. package/cjs/isNode.js +23 -0
  15. package/cjs/object/createConstructor.js +59 -0
  16. package/cjs/performance.js +138 -0
  17. package/cjs/regexp/autoEscapedRegExp.js +44 -0
  18. package/cjs/regexp/escapeRegExp.js +22 -0
  19. package/cjs/regexp/parse.js +31 -0
  20. package/cjs/sleep.js +37 -0
  21. package/es/array/difference.d.ts +29 -0
  22. package/es/array/difference.js +46 -0
  23. package/es/array/index.d.ts +125 -0
  24. package/es/array/index.js +127 -0
  25. package/es/array/intersection.d.ts +17 -0
  26. package/es/array/intersection.js +38 -0
  27. package/es/array/symmetricDifference.d.ts +27 -0
  28. package/es/array/symmetricDifference.js +43 -0
  29. package/es/array/union.d.ts +39 -0
  30. package/es/array/union.js +60 -0
  31. package/es/className.d.ts +26 -0
  32. package/es/className.js +52 -0
  33. package/es/createBezier.d.ts +64 -0
  34. package/es/createBezier.js +133 -0
  35. package/es/getRandomNumber.d.ts +24 -0
  36. package/es/getRandomNumber.js +67 -0
  37. package/es/getRandomString.d.ts +73 -0
  38. package/es/getRandomString.js +141 -0
  39. package/es/index.d.ts +12 -0
  40. package/es/index.js +15 -0
  41. package/es/isNode.d.ts +8 -0
  42. package/es/isNode.js +20 -0
  43. package/es/object/createConstructor.d.ts +47 -0
  44. package/es/object/createConstructor.js +56 -0
  45. package/es/object/index.d.ts +2 -0
  46. package/es/performance.d.ts +61 -0
  47. package/es/performance.js +135 -0
  48. package/es/regexp/autoEscapedRegExp.d.ts +28 -0
  49. package/es/regexp/autoEscapedRegExp.js +42 -0
  50. package/es/regexp/escapeRegExp.d.ts +16 -0
  51. package/es/regexp/escapeRegExp.js +20 -0
  52. package/es/regexp/index.d.ts +2 -0
  53. package/es/regexp/parse.d.ts +6 -0
  54. package/es/regexp/parse.js +29 -0
  55. package/es/regexp/types.d.ts +10 -0
  56. package/es/sleep.d.ts +25 -0
  57. package/es/sleep.js +35 -0
  58. package/package.json +118 -0
@@ -0,0 +1,135 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * @file createBezier.ts
5
+ * @description 生成贝尔赛曲线
6
+ * @author Mr.MudBean <Mr.MudBean@outlook.com>
7
+ * @copyright 2026 ©️ Mr.MudBean
8
+ * @since 2026-03-26 11:24
9
+ * @version 2.0.2
10
+ * @lastModified 2026-06-11 19:07
11
+ *
12
+ * ## [贝尔赛曲线](https://developer.mozilla.org/zh-CN/docs/Web/CSS/Reference/Values/easing-function#%E4%B8%89%E6%AC%A1%E8%B4%9D%E5%A1%9E%E5%B0%94%E7%BC%93%E5%8A%A8%E5%87%BD%E6%95%B0)
13
+ *
14
+ * 一种通过控制点生成光滑曲线的数学参数曲线,是平滑插值曲线。
15
+ *
16
+ * 广泛应用于计算机图像学、字体设计、动画游戏开发、工业设计和医学图像处理。
17
+ *
18
+ * 常见的贝尔赛曲线类型有二次和三次,其中三次贝尔赛曲线使用最多。曲线具有端点插值、凸包性。
19
+ *
20
+ */
21
+ /**
22
+ * # 在 JS 中模拟 CSS cubic-bezier(p1x, p1y, p2x, p2y)
23
+ *
24
+ * @param p1x - 第一个控制点 X
25
+ * @param p1y - 第一个控制点 Y
26
+ * @param p2x - 第二个控制点 X
27
+ * @param p2y - 第二个控制点 Y
28
+ * @returns 一个接收时间 t (0-1) 返回进度值 (0-1 或超出) 的函数
29
+ * @example
30
+ * ```ts
31
+ * // --- 使用示例 ---
32
+ *
33
+ * // 1. 定义一个类似 CSS 'ease-in-out' 的曲线: cubic-bezier(0.42, 0, 0.58, 1)
34
+ * const myEaseInOut = createBezier(0.42, 0, 0.58, 1);
35
+ *
36
+ * // 2. 定义一个带回弹效果的曲线: cubic-bezier(0.68, -0.55, 0.27, 1.55)
37
+ * const myElastic = createBezier(0.68, -0.55, 0.27, 1.55);
38
+ *
39
+ * // 3. 在 JS 动画循环中使用
40
+ * let startTime = null;
41
+ * const duration = 1000; // 1秒
42
+ * const element = document.getElementById('box');
43
+ *
44
+ * function animate(timestamp) {
45
+ * if (!startTime) startTime = timestamp;
46
+ * const elapsed = timestamp - startTime;
47
+ *
48
+ * // 计算归一化时间 (0 到 1)
49
+ * let rawTime = Math.min(elapsed / duration, 1);
50
+ *
51
+ * // 【关键点】将线性时间 rawTime 传入贝塞尔函数,得到非线性进度
52
+ * const progress = myElastic(rawTime);
53
+ *
54
+ * // 应用进度 (例如移动距离)
55
+ * const distance = 300 * progress;
56
+ * element.style.transform = `translateX(${distance}px)`;
57
+ *
58
+ * if (elapsed < duration) {
59
+ * requestAnimationFrame(animate);
60
+ * }
61
+ * }
62
+ *
63
+ * requestAnimationFrame(animate);
64
+ * ```
65
+ */
66
+ function createBezier(p1x, p1y, p2x, p2y) {
67
+ // 三次贝塞尔曲线公式: B(t) = (1-t)^3 * P0 + 3(1-t)^2*t * P1 + 3(1-t)*t^2 * P2 + t^3 * P3
68
+ // 这里 P0=(0,0), P3=(1,1)
69
+ const cx = 3 * p1x;
70
+ const bx = 3 * (p2x - p1x) - cx;
71
+ const ax = 1 - cx - bx;
72
+ const cy = 3 * p1y;
73
+ const by = 3 * (p2y - p1y) - cy;
74
+ const ay = 1 - cy - by;
75
+ // 计算给定 t 的 x 值
76
+ /**
77
+ * @param t
78
+ */
79
+ function sampleCurveX(t) {
80
+ return ((ax * t + bx) * t + cx) * t;
81
+ }
82
+ /**
83
+ * ### 计算给定 t 的 y 值
84
+ * @param t 时间进度
85
+ */
86
+ function sampleCurveY(t) {
87
+ return ((ay * t + by) * t + cy) * t;
88
+ }
89
+ /**
90
+ * ### 核心难点:已知 x (时间),求 t。因为 x(t) 是单调的,可以用牛顿迭代法求解
91
+ * @param x 时间进度
92
+ */
93
+ function getTForX(x) {
94
+ let t0, t1, t2, x2, d2;
95
+ // 初始猜测
96
+ t2 = x;
97
+ // 牛顿迭代法 (通常 8 次足够精确)
98
+ for (let i = 0; i < 8; i++) {
99
+ x2 = sampleCurveX(t2) - x;
100
+ if (Math.abs(x2) < 1e-6)
101
+ return t2;
102
+ d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
103
+ if (Math.abs(d2) < 1e-6)
104
+ break;
105
+ t2 = t2 - x2 / d2;
106
+ }
107
+ // 如果牛顿法失败,退化为二分法
108
+ t0 = 0;
109
+ t1 = 1;
110
+ t2 = x;
111
+ while (t0 < t1) {
112
+ x2 = sampleCurveX(t2);
113
+ if (Math.abs(x2 - x) < 1e-6)
114
+ return t2;
115
+ if (x > x2)
116
+ t0 = t2;
117
+ else
118
+ t1 = t2;
119
+ t2 = (t1 - t0) * 0.5 + t0;
120
+ }
121
+ return t2;
122
+ }
123
+ // 返回最终的计算函数
124
+ return function (t) {
125
+ // 边界处理:CSS 允许 t < 0 或 t > 1 (产生回弹效果)
126
+ if (t <= 0)
127
+ return sampleCurveY(0);
128
+ if (t >= 1)
129
+ return sampleCurveY(1);
130
+ const realT = getTForX(t);
131
+ return sampleCurveY(realT);
132
+ };
133
+ }
134
+
135
+ exports.createBezier = createBezier;
@@ -0,0 +1,70 @@
1
+ 'use strict';
2
+
3
+ var is = require('@mudbean/is');
4
+
5
+ /**
6
+ * 获取随机数
7
+ */
8
+ /**
9
+ * # 获取一个随机的整数类型
10
+ *
11
+ * 您可以传入两个参数并获取它们之间的任意数字,返回值<span style="color:#ff0;">*会包含端值*</span>
12
+ *
13
+ * 如果只传递一个参数,则如果提供的值为负数,则得到一个小于(或大于)该数字的整数
14
+ *
15
+ * @param max 较大值 ,不允许为`NaN`
16
+ * @param min 较小值,不允许为 `NaN`
17
+ * @returns 任意的整数
18
+ */
19
+ function getRandomInt(max = 1, min = 0) {
20
+ // 判断是否为 NaN 或 不是数字
21
+ if (!isFinite(max) ||
22
+ !isFinite(min) ||
23
+ is.isNaN(max) ||
24
+ is.isNaN(min) ||
25
+ !is.isNumber(max) ||
26
+ !is.isNumber(min)) {
27
+ throw new TypeError('getRandomInt: max or min is NaN or is not a number');
28
+ }
29
+ /** 获取最小值 */
30
+ let _min = Math.ceil(Number(min)),
31
+ /** 获取最大值 */
32
+ _max = Math.floor(Number(max));
33
+ // 两值相等时,直接返回最大值
34
+ if (_max === _min)
35
+ return _max;
36
+ // 两值交换
37
+ if (_min > _max)
38
+ [_max, _min] = [_min, _max];
39
+ return Math.round(Math.random() * (_max - _min) + _min);
40
+ }
41
+ /**
42
+ * # 获取任意的浮点数
43
+ *
44
+ * 您可以传入两个参数并获取它们之间的任意数字
45
+ *
46
+ * 如果只传入一个参数,则如果提供的值为负数,则获取小于(或大于)该数字的浮点数
47
+ *
48
+ * @param max 较大数,缺省值为 1
49
+ * @param min 较小值,缺省值为 0
50
+ * @returns 任意的浮点数
51
+ */
52
+ function getRandomFloat(max = 1, min = 0) {
53
+ // 判断是否为 NaN 或 不是数字
54
+ if (!isFinite(max) ||
55
+ !isFinite(min) ||
56
+ is.isNaN(max) ||
57
+ is.isNaN(min) ||
58
+ !is.isNumber(max) ||
59
+ !is.isNumber(min)) {
60
+ throw new TypeError('getRandomInt: max or min is NaN or is not a number');
61
+ }
62
+ if (max == min)
63
+ max++;
64
+ if (min > max)
65
+ [max, min] = [min, max];
66
+ return Math.random() * (max - min) + min;
67
+ }
68
+
69
+ exports.getRandomFloat = getRandomFloat;
70
+ exports.getRandomInt = getRandomInt;
@@ -0,0 +1,143 @@
1
+ 'use strict';
2
+
3
+ var is = require('@mudbean/is');
4
+ var createConstructor = require('./object/createConstructor.js');
5
+ var getRandomNumber = require('./getRandomNumber.js');
6
+
7
+ /**
8
+ * 获取随机字符串
9
+ */
10
+ /**
11
+ * # 获取简单的随机字符串
12
+ *
13
+ * ```ts
14
+ * type RandomStringOptions = {
15
+ * length?: number; // 字符串长度
16
+ * chars?: string; // 包含英文字符
17
+ * includeNumbers?: boolean; // 包含数字
18
+ * includeUppercaseLetters?: boolean; // 包含大写字符
19
+ * includeSpecial?: boolean; // 包含特殊字符
20
+ * type?: 'string' | 'uuid'; // 生成类型
21
+ * }
22
+ * ```
23
+ *
24
+ * @param options - 字符串生成参数
25
+ * @returns - 随机字符串
26
+ * @example
27
+ * ```ts
28
+ * import { getRandomString } from '@mudbean/utils';
29
+ *
30
+ * // 获取简单的随机字符串
31
+ * // 'abcdefg'
32
+ * getRandomString(7);
33
+ *
34
+ * // 获取随机的字符串
35
+ * getRandomString({
36
+ * length: 7,
37
+ * })
38
+ * ```
39
+ */
40
+ function getRandomString(options) {
41
+ // 验证输入参数
42
+ if (
43
+ // 参数类型错误
44
+ (!is.isPlainObject(options) && !is.isNumber(options)) ||
45
+ // 参数为 NaN
46
+ (is.isNumber(options) && is.isNaN(options)) ||
47
+ // 参数为数字时为无穷大
48
+ (is.isNumber(options) && !isFinite(options)) ||
49
+ // 参数为数字时为非整数
50
+ (is.isNumber(options) && !Number.isInteger(options)) ||
51
+ // 参数为数字时为负数
52
+ (is.isNumber(options) && Number.isInteger(options) && options < 1) ||
53
+ // 参数为数值然而却小于 1
54
+ (is.isNumber(options) && options < 1) ||
55
+ // 参数为对象但是 length 属性非数值
56
+ (is.isPlainObject(options) &&
57
+ (!is.isNumber(options.length) ||
58
+ options.length < 1 ||
59
+ !Number.isInteger(options.length))))
60
+ throw new TypeError('参数类型错误 ❌ (getRandomString)');
61
+ const initOptions = {
62
+ length: 32,
63
+ chars: 'abcdefghijklmnopqrstuvwxyz',
64
+ chars2: '0123456789',
65
+ chars3: '!@#$%^&*()_+~`|}{[]:;?><,./-=',
66
+ type: 'string',
67
+ includeUppercaseLetters: false,
68
+ includeNumbers: false,
69
+ includeSpecial: false,
70
+ };
71
+ /// 生成 UUID
72
+ if (initOptions.type === 'uuid')
73
+ return crypto.randomUUID();
74
+ // 验证输入参数
75
+ if (is.isNumber(options) && Number.isInteger(options) && options > 0)
76
+ createConstructor.ObjectAssign(initOptions, { length: options });
77
+ if (is.isPlainObject(options)) {
78
+ createConstructor.ObjectAssign(initOptions, options);
79
+ initOptions.length = initOptions.length < 1 ? 32 : initOptions.length;
80
+ }
81
+ /** 生成随机字符串 */
82
+ const templateCharsArr = initOptions.chars.split('');
83
+ // 添加大写字母
84
+ if (initOptions.includeUppercaseLetters)
85
+ interleaveString(templateCharsArr, initOptions.chars.toUpperCase());
86
+ // 添加数字
87
+ if (initOptions.includeNumbers)
88
+ interleaveString(templateCharsArr, initOptions.chars2);
89
+ // 添加特殊字符
90
+ if (initOptions.includeSpecial)
91
+ interleaveString(templateCharsArr, initOptions.chars3);
92
+ /** 结果字符串 */
93
+ let result = '';
94
+ /** 混淆后的字符串 */
95
+ const str = templateCharsArr.join('');
96
+ /** 混淆后字符长度 */
97
+ const strLen = str.length;
98
+ if (globalThis && globalThis.crypto && globalThis.crypto.getRandomValues) {
99
+ // 使用密码学安全的随机数生成器
100
+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(initOptions.length));
101
+ /** 获取最后的 chars 数据 */
102
+ // 循环遍历
103
+ bytes.forEach(byte => (result += str[byte % strLen]));
104
+ }
105
+ else {
106
+ for (let i = 0; i < initOptions.length; i++)
107
+ result += str[getRandomNumber.getRandomInt(strLen - 1)];
108
+ }
109
+ /**
110
+ * # 字符串交叉函数
111
+ *
112
+ * 非线形串交叉,对相交叉
113
+ *
114
+ * @param str1 - 字符串1
115
+ * @param str2 - 字符串2
116
+ * @returns - 交叉后的字符串
117
+ * @example
118
+ *
119
+ * ```ts
120
+ * interleaveString('abc', '123') // 'a1b2c3'
121
+ * ```
122
+ */
123
+ function interleaveString(str1, str2) {
124
+ const str1Length = str1.length, str2Length = str2.length;
125
+ const maxLength = Math.max(str1Length, str2Length);
126
+ for (let i = 0; i < maxLength; i++) {
127
+ if (i < str1Length && !is.isUndefined(str2[i])) {
128
+ str1[i] += str2[i];
129
+ }
130
+ else if (i < str2Length) {
131
+ str1[i] = str2[i];
132
+ }
133
+ }
134
+ }
135
+ /// 结果字符串不包含字符
136
+ if (!/[a-zA-Z]/.test(result))
137
+ return String.fromCharCode(getRandomNumber.getRandomInt(97, 122)).concat(result.slice(1));
138
+ while (!/^[a-zA-Z]$/.test(result[0]))
139
+ result = result.slice(1) + result[0];
140
+ return result;
141
+ }
142
+
143
+ exports.getRandomString = getRandomString;
package/cjs/index.js ADDED
@@ -0,0 +1,40 @@
1
+ 'use strict';
2
+
3
+ var className = require('./className.js');
4
+ var createConstructor = require('./object/createConstructor.js');
5
+ var getRandomNumber = require('./getRandomNumber.js');
6
+ var getRandomString = require('./getRandomString.js');
7
+ var performance = require('./performance.js');
8
+ var escapeRegExp = require('./regexp/escapeRegExp.js');
9
+ var autoEscapedRegExp = require('./regexp/autoEscapedRegExp.js');
10
+ var isNode = require('./isNode.js');
11
+ var index = require('./array/index.js');
12
+ var sleep = require('./sleep.js');
13
+ var createBezier = require('./createBezier.js');
14
+ var difference = require('./array/difference.js');
15
+ var intersection = require('./array/intersection.js');
16
+ var symmetricDifference = require('./array/symmetricDifference.js');
17
+ var union = require('./array/union.js');
18
+
19
+
20
+
21
+ exports.toLowerCamelCase = className.toLowerCamelCase;
22
+ exports.toSplitCase = className.toSplitCase;
23
+ exports.ObjectAssign = createConstructor.ObjectAssign;
24
+ exports.createConstructor = createConstructor.createConstructor;
25
+ exports.getRandomFloat = getRandomNumber.getRandomFloat;
26
+ exports.getRandomInt = getRandomNumber.getRandomInt;
27
+ exports.getRandomString = getRandomString.getRandomString;
28
+ exports.debounce = performance.debounce;
29
+ exports.throttle = performance.throttle;
30
+ exports.escapeRegExp = escapeRegExp.escapeRegExp;
31
+ exports.autoEscapedRegExp = autoEscapedRegExp.autoEscapedRegExp;
32
+ exports.isBrowser = isNode.isBrowser;
33
+ exports.isNode = isNode.isNode;
34
+ exports.enArr = index.enArr;
35
+ exports.sleep = sleep.sleep;
36
+ exports.createBezier = createBezier.createBezier;
37
+ exports.difference = difference.difference;
38
+ exports.intersection = intersection.intersection;
39
+ exports.symmetricDifference = symmetricDifference.symmetricDifference;
40
+ exports.union = union.union;
package/cjs/isNode.js ADDED
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+
3
+ var is = require('@mudbean/is');
4
+
5
+ /**
6
+ * # 判断当前环境是否为 node 环境
7
+ */
8
+ function isNode() {
9
+ return !is.isUndefined((globalThis &&
10
+ globalThis.process &&
11
+ globalThis.process.versions &&
12
+ globalThis.process.versions.node) ||
13
+ undefined);
14
+ }
15
+ /**
16
+ * # 是否为浏览器环境
17
+ */
18
+ function isBrowser() {
19
+ return !isNode();
20
+ }
21
+
22
+ exports.isBrowser = isBrowser;
23
+ exports.isNode = isNode;
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * # 构建一个 Constructor 构造函数
5
+ *
6
+ * 接收一个构造函数,然后返回 TS 能识别的构造函数自身
7
+ *
8
+ * 函数本身并没有执行任何逻辑,仅是简单的返回了实参自身
9
+ *
10
+ * 而经过该函数的包装,构造函数成了能够被 TS 识别为可用 new 实例的构造函数
11
+ *
12
+ * @param constructor - 传入一个构造函数
13
+ * @returns 返回传入的构造函数
14
+ * @example
15
+ * ```ts
16
+ * import { createConstructor } from "@mudbean/utils";
17
+ *
18
+ * type Tom = {
19
+ * a: number
20
+ * }
21
+ *
22
+ * function _Tom (this: TomType): Tom {
23
+ * this.a = 1;
24
+ *
25
+ * return this;
26
+ * }
27
+ *
28
+ * // 逻辑上没有错,但是会造成 ts 显示
29
+ * // 其目标缺少构造签名的 "new" 表达式隐式具有 "any" 类型。ts(7009)
30
+ * const a = new _Tom();
31
+ *
32
+ * const tomConstructor = createConstructor(_tom);
33
+ *
34
+ * const b = new tomConstructor(); // 这时就不会显示错误
35
+ * ```
36
+ */
37
+ function createConstructor(constructor) {
38
+ constructor.prototype.apply = Function.apply;
39
+ constructor.prototype.bind = Function.bind;
40
+ constructor.prototype.call = Function.call;
41
+ constructor.prototype.length = Function.length;
42
+ // constructor.prototype.arguments = Function.arguments;
43
+ constructor.prototype.name = Function.name;
44
+ constructor.prototype.toString = Function.toString;
45
+ return constructor;
46
+ }
47
+ /**
48
+ * # 对象的 assign 用法
49
+ * @param target
50
+ * @param bar
51
+ */
52
+ function ObjectAssign(target, bar) {
53
+ const keys = Object.keys(bar);
54
+ keys.forEach(key => (target[key] = bar[key]));
55
+ return target;
56
+ }
57
+
58
+ exports.ObjectAssign = ObjectAssign;
59
+ exports.createConstructor = createConstructor;
@@ -0,0 +1,138 @@
1
+ 'use strict';
2
+
3
+ var is = require('@mudbean/is');
4
+
5
+ /**
6
+ * 防抖和节流
7
+ */
8
+ /**
9
+ * # 防抖
10
+ *
11
+ * @param callback 回调函数
12
+ * @param options 延迟时间(毫秒),默认 200 (ms) 或包含 this 的配置
13
+ * @returns 返回的闭包函数
14
+ * @example
15
+ *
16
+ * ```ts
17
+ * import { debounce } from '@mudbean/utils';
18
+ *
19
+ * const debounce = (callback: Function, delay = 300) => {
20
+ * let timer: any = null
21
+ *
22
+ * return (...args: any[]) => clearTimeout(timer)
23
+ * }
24
+ *
25
+ * debounce(); // 未执行
26
+ * debounce(); // 未执行
27
+ * debounce(); // 未执行
28
+ * debounce(); // 执行
29
+ * ```
30
+ */
31
+ function debounce(callback, options = 200) {
32
+ if (!is.isFunction(callback))
33
+ throw new TypeError('callback must be a function');
34
+ if (is.isNumber(options))
35
+ options = {
36
+ delay: options,
37
+ this: null,
38
+ };
39
+ if (is.isUndefined(options.delay) ||
40
+ !isFinite(options.delay) ||
41
+ options.delay < 0)
42
+ // 强制转换非数值
43
+ options.delay = 200;
44
+ /** 定时器返回的 id */
45
+ let timeoutId;
46
+ const clear = () => {
47
+ if (timeoutId) {
48
+ clearTimeout(timeoutId);
49
+ timeoutId = undefined;
50
+ }
51
+ };
52
+ const result = (...args) => {
53
+ clear();
54
+ timeoutId = setTimeout(() => {
55
+ try {
56
+ const _this = options && options.this ? options.this : null;
57
+ // 由于 Reflect.apply 并不能在 ES5 中使用,所以我们并不能保证能执行成功
58
+ callback.apply(_this, args);
59
+ // Reflect.apply(callback, options?.this ?? null, args);
60
+ }
61
+ catch (error) {
62
+ console.log('Debounce callback throw an error', error);
63
+ }
64
+ }, Math.max(options.delay || 5, 5));
65
+ };
66
+ result.cancel = () => clear();
67
+ return result;
68
+ }
69
+ /**
70
+ * # 节流
71
+ *
72
+ * @param callback 回调函数
73
+ * @param options 延迟时间(毫秒),默认 200 (ms) 或设置 this
74
+ * @returns 返回的闭包函数
75
+ * @example
76
+ *
77
+ * ```ts
78
+ * import { throttle , sleep } form "@mudbean/utils";
79
+ *
80
+ * const a_throttle_fn = throttle(()=> {
81
+ * console.log("hello");
82
+ * }, 1200);
83
+ *
84
+ * a_throttle_fn(); // 正常打印
85
+ * a_throttle_fn(); // 跳过打印
86
+ * await sleep(1200); // 等待 1200ms
87
+ * a_throttle_fn(); // 正常打印
88
+ * a_throttle_fn(); // 跳过打印
89
+ * ```
90
+ */
91
+ function throttle(callback, options = 200) {
92
+ if (!is.isFunction(callback))
93
+ throw new TypeError('callback must be a function');
94
+ if (is.isNumber(options))
95
+ options = {
96
+ delay: options,
97
+ this: null,
98
+ };
99
+ if (is.isUndefined(options.delay) ||
100
+ !isFinite(options.delay) ||
101
+ options.delay < 0)
102
+ // 强制转换非数值
103
+ options.delay = 200;
104
+ /** 延迟控制插销 */
105
+ let inThrottle = false;
106
+ /** 延迟控制 */
107
+ let timeoutId = null;
108
+ const delay = options && options.delay ? options.delay : 5;
109
+ const throttled = (...args) => {
110
+ if (inThrottle)
111
+ return;
112
+ try {
113
+ const _this = options && options.this ? options.this : null;
114
+ callback.apply(_this, args);
115
+ }
116
+ catch (error) {
117
+ console.error('Throttle 执行回调抛出问题', error);
118
+ }
119
+ inThrottle = true;
120
+ if (!is.isNull(timeoutId))
121
+ clearTimeout(timeoutId);
122
+ timeoutId = setTimeout(() => {
123
+ inThrottle = false;
124
+ timeoutId = null;
125
+ }, Math.max(delay, 5));
126
+ };
127
+ throttled.cancel = () => {
128
+ if (!is.isNull(timeoutId)) {
129
+ clearTimeout(timeoutId);
130
+ }
131
+ inThrottle = false;
132
+ timeoutId = null;
133
+ };
134
+ return throttled;
135
+ }
136
+
137
+ exports.debounce = debounce;
138
+ exports.throttle = throttle;
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+
3
+ var is = require('@mudbean/is');
4
+ var escapeRegExp = require('./escapeRegExp.js');
5
+ var parse = require('./parse.js');
6
+
7
+ /**
8
+ * # 适用于简单的文本字符串自动转化为简单模式正则表达式
9
+ *
10
+ * *若字符串包含且需保留字符类、组、反向引用、量词等时,该方法可能不适用*
11
+ *
12
+ * @param pattern 待转化的文本字符串
13
+ * @param options 转化选项。 为文本字符串时,默认为正则表达式的标志,还可指定是否匹配开头或结尾
14
+ * @returns 正则表达式
15
+ * @example
16
+ * ```ts
17
+ * import { autoEscapedRegExp } from '@mudbean/utils';
18
+ *
19
+ * autoEscapedRegExp('abc'); // => /abc/
20
+ * autoEscapedRegExp('abc', 'gim'); // => /abc/gim
21
+ * autoEscapedRegExp('abc', { flags: 'g', start: true }); // => /^abc/g
22
+ * autoEscapedRegExp('abc', { flags: 'g', end: true }); // => /abc$/g
23
+ * autoEscapedRegExp('abc', { start: true, end: true }); // => /^abc$/
24
+ *
25
+ * // 转化特殊字符类、组、反向引用、量词等
26
+ * // 无法保留匹配规则
27
+ * autoEscapedRegExp('a-zA-Z0-9'); // => /a-zA-Z0-9/
28
+ * autoEscapedRegExp('a-zA-Z0-9', 'g'); // => /a-zA-Z0-9/g
29
+ * autoEscapedRegExp('[a-zA-Z0-9]'); // => /\[a-zA-Z0-9\]/
30
+ * autoEscapedRegExp('^[a-zA-Z0-9]+$'); // => /\^\[a-zA-Z0-9\]\$/
31
+ * ```
32
+ */
33
+ function autoEscapedRegExp(pattern, options) {
34
+ if (!is.isString(pattern))
35
+ throw new TypeError('pattern must be a 字符串');
36
+ pattern = escapeRegExp.escapeRegExp(pattern);
37
+ /** 简单转化 */
38
+ if (is.isUndefined(options))
39
+ return new RegExp(pattern);
40
+ options = parse.parse(options);
41
+ return new RegExp(`${options.start ? '^' : ''}${pattern}${options.end ? '$' : ''}`, options.flags);
42
+ }
43
+
44
+ exports.autoEscapedRegExp = autoEscapedRegExp;
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * # 将一个字符串转化为符合正则要求的字符串
5
+ *
6
+ * @param str 需要转义的字符串
7
+ * @requires escapeRegExp 转化后字符串
8
+ * @example
9
+ * ```ts
10
+ * import { escapeRegExp } from '@mudbean/utils';
11
+ *
12
+ * escapeRegExp('a.b.c'); // 'a\\.b\\.c'
13
+ * escapeRegExp('a\\.b\\.c'); // 'a\\\\.b\\\\.c'
14
+ * escapeRegExp('[a-z]'); // '\\[a-z\\]'
15
+ * escapeRegExp('^abc$'); // '\\^abc\\$'
16
+ * ```
17
+ */
18
+ function escapeRegExp(str) {
19
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
20
+ }
21
+
22
+ exports.escapeRegExp = escapeRegExp;