@deot/helper-utils 1.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.
@@ -0,0 +1,344 @@
1
+ const asterisk = (value, from, length) => {
2
+ from = from || 3;
3
+ length = length || 4;
4
+ let repeat = length;
5
+ let content = value.substring(0, from);
6
+ while (repeat) {
7
+ content += "*";
8
+ repeat--;
9
+ }
10
+ content += value.substring(from + length);
11
+ return content;
12
+ };
13
+
14
+ const autoCatch = async (impl, options = {}) => {
15
+ const { onError = console.error } = options;
16
+ let target = impl;
17
+ typeof target === "function" && (target = target());
18
+ try {
19
+ const e = await target;
20
+ return e;
21
+ } catch (e) {
22
+ onError(e);
23
+ }
24
+ };
25
+
26
+ const getMime = (filename) => {
27
+ let ext;
28
+ if (typeof filename === "string" && filename.includes(".")) {
29
+ ext = filename.split(".").pop();
30
+ }
31
+ return ext ? `image/${ext}` : "image/jpeg";
32
+ };
33
+ const dataURLToFile = (dataURL, filename, filetype) => {
34
+ const hasPrefix = /data:[^;]+;[^,]+,/g.test(dataURL);
35
+ if (!hasPrefix) {
36
+ dataURL = `data:${filetype || getMime(filename)};base64,${dataURL}`;
37
+ }
38
+ let [suffix, dataURL$] = dataURL.split(",");
39
+ let mime = suffix.match(/:(.*?);/)?.[1];
40
+ let bstr = window.atob(dataURL$);
41
+ let n = bstr.length;
42
+ let u8arr = new Uint8Array(n);
43
+ while (n--) {
44
+ u8arr[n] = bstr.charCodeAt(n);
45
+ }
46
+ return new File([u8arr], filename || "__filename", { type: mime });
47
+ };
48
+
49
+ const canvasToImage = (canvas, filename) => {
50
+ const dataURL = canvas.toDataURL("image/png");
51
+ return new Promise((resolve) => {
52
+ let result = {
53
+ dataURL
54
+ };
55
+ if (typeof filename === "string") {
56
+ result.file = dataURLToFile(dataURL, filename);
57
+ }
58
+ resolve(result);
59
+ });
60
+ };
61
+
62
+ const cloneDeepEasier = (source) => JSON.parse(JSON.stringify(source));
63
+
64
+ const compressImage = (file, options) => {
65
+ const { width, height, filetype = "image/jpeg", encoderOptions } = options || {};
66
+ return new Promise((resolve, reject) => {
67
+ const el = new Image();
68
+ const reader = new FileReader();
69
+ reader.readAsDataURL(file);
70
+ reader.onload = (e) => {
71
+ el.src = e.target.result;
72
+ };
73
+ const canvas = document.createElement("canvas");
74
+ const context = canvas.getContext("2d");
75
+ el.onload = () => {
76
+ const originWidth = el.width;
77
+ const originHeight = el.height;
78
+ const maxWidth = width || originWidth;
79
+ const maxHeight = height || originHeight;
80
+ let targetWidth = originWidth;
81
+ let targetHeight = originHeight;
82
+ if (originWidth > maxWidth || originHeight > maxHeight) {
83
+ if (originWidth / originHeight > maxWidth / maxHeight) {
84
+ targetWidth = maxWidth;
85
+ targetHeight = Math.round(maxWidth * (originHeight / originWidth));
86
+ } else {
87
+ targetHeight = maxHeight;
88
+ targetWidth = Math.round(maxHeight * (originWidth / originHeight));
89
+ }
90
+ }
91
+ canvas.width = targetWidth;
92
+ canvas.height = targetHeight;
93
+ context.clearRect(0, 0, targetWidth, targetHeight);
94
+ context.drawImage(el, 0, 0, targetWidth, targetHeight);
95
+ const dataURL = canvas.toDataURL(filetype, encoderOptions);
96
+ const compressFile = dataURLToFile(dataURL, file.name);
97
+ resolve({
98
+ dataURL,
99
+ file: compressFile
100
+ });
101
+ };
102
+ el.onerror = (e) => {
103
+ reject(e);
104
+ };
105
+ });
106
+ };
107
+
108
+ const debounce = (original, wait, options) => {
109
+ const { leading, trailing = true, throttle } = options || {};
110
+ let timer;
111
+ let invoke;
112
+ let cancel = () => {
113
+ timer && clearTimeout(timer);
114
+ timer = null;
115
+ };
116
+ let start = () => {
117
+ timer = setTimeout(() => {
118
+ timer = null;
119
+ trailing && invoke && invoke();
120
+ }, wait);
121
+ };
122
+ const fn = function(...args) {
123
+ invoke = () => {
124
+ original.apply(this, args);
125
+ invoke = null;
126
+ };
127
+ if (!wait && throttle)
128
+ return invoke();
129
+ if (!timer) {
130
+ leading && invoke();
131
+ start();
132
+ } else if (!throttle) {
133
+ cancel();
134
+ start();
135
+ }
136
+ };
137
+ fn.cancel = () => {
138
+ cancel();
139
+ invoke = null;
140
+ };
141
+ fn.flush = () => {
142
+ cancel();
143
+ trailing && invoke && invoke();
144
+ };
145
+ return fn;
146
+ };
147
+
148
+ const def = (target, key, value, options) => {
149
+ Object.defineProperty(target, key, {
150
+ value,
151
+ enumerable: false,
152
+ writable: true,
153
+ configurable: true,
154
+ ...options
155
+ });
156
+ };
157
+
158
+ const getPropByPath = (target, path) => {
159
+ let o = target;
160
+ path = path.replace(/\[(\w+)\]/g, ".$1");
161
+ path = path.replace(/^\./, "");
162
+ let keyArr = path.split(".");
163
+ let i = 0;
164
+ for (let len = keyArr.length; i < len - 1; ++i) {
165
+ let key = keyArr[i];
166
+ try {
167
+ if (key in o) {
168
+ o = o[key];
169
+ } else {
170
+ throw new Error();
171
+ }
172
+ } catch {
173
+ throw new Error("无效路径!");
174
+ }
175
+ }
176
+ return {
177
+ o,
178
+ k: keyArr[i],
179
+ v: o[keyArr[i]]
180
+ };
181
+ };
182
+
183
+ const timestamp = +/* @__PURE__ */ new Date();
184
+ let index = 0;
185
+ const getUid = (prefix) => {
186
+ return `${prefix ? `${prefix}-` : ""}${timestamp}-${++index}`;
187
+ };
188
+
189
+ const hasOwn = (target, key) => Object.prototype.hasOwnProperty.call(target, key);
190
+
191
+ const isObj = (target) => typeof target === "object";
192
+
193
+ const getDigit = (integer) => {
194
+ let digit = -1;
195
+ while (integer >= 1) {
196
+ digit++;
197
+ integer /= 10;
198
+ }
199
+ return digit;
200
+ };
201
+ const addWan = (integer, num, mutiple, decimalDigit) => {
202
+ let digit = getDigit(integer);
203
+ if (digit > 3) {
204
+ let remainder = digit % 8;
205
+ if (remainder >= 5) {
206
+ remainder = 4;
207
+ }
208
+ return Math.round(num / Math.pow(10, remainder + mutiple - decimalDigit)) / Math.pow(10, decimalDigit) + "万";
209
+ } else {
210
+ return Math.round(num / Math.pow(10, mutiple - decimalDigit)) / Math.pow(10, decimalDigit) + "";
211
+ }
212
+ };
213
+ const numberToUnit = (number, decimalDigit) => {
214
+ if (number > Number.MAX_SAFE_INTEGER) {
215
+ number = Number.MAX_SAFE_INTEGER;
216
+ }
217
+ decimalDigit = decimalDigit == null ? 2 : decimalDigit;
218
+ let integer = Math.floor(number);
219
+ let digit = getDigit(integer);
220
+ let unit = [];
221
+ if (digit > 3) {
222
+ let multiple = Math.floor(digit / 8);
223
+ if (multiple >= 1) {
224
+ let tmp = Math.round(integer / Math.pow(10, 8 * multiple));
225
+ unit.push(addWan(tmp, number, 8 * multiple, decimalDigit));
226
+ for (let i = 0; i < multiple; i++) {
227
+ unit.push("亿");
228
+ }
229
+ return unit.join("");
230
+ } else {
231
+ return addWan(integer, number, 0, decimalDigit);
232
+ }
233
+ } else {
234
+ return number;
235
+ }
236
+ };
237
+
238
+ const preZero = (num) => {
239
+ if (num < 10 && num > 0) {
240
+ return "0" + num;
241
+ } else if (num <= 0) {
242
+ return "00";
243
+ }
244
+ return "" + num;
245
+ };
246
+
247
+ const raf = typeof window !== "undefined" && window.requestAnimationFrame || ((fn) => setTimeout(fn, 16));
248
+
249
+ const range = (min, max) => {
250
+ return Math.floor(Math.random() * (max - min + 1) + min);
251
+ };
252
+ const probs = (weights) => {
253
+ let sum = weights.reduce((pre, cur) => pre + (!cur || cur <= 0 ? 0 : cur), 0);
254
+ if (!sum) {
255
+ throw new Error("不可能得到索引值");
256
+ }
257
+ let probs$ = weights.map((i) => i / sum);
258
+ let index = 0;
259
+ let r = Math.random();
260
+ while (r > 0) {
261
+ r -= probs$[index];
262
+ index++;
263
+ }
264
+ index--;
265
+ return index;
266
+ };
267
+
268
+ const sleep = (wait, immediate) => {
269
+ let duration;
270
+ if (typeof wait === "object") {
271
+ duration = range(wait.min, wait.max);
272
+ } else {
273
+ duration = wait || 0;
274
+ }
275
+ return new Promise((r) => {
276
+ let timer = setTimeout(r, duration);
277
+ immediate && immediate(timer, duration, r);
278
+ });
279
+ };
280
+
281
+ const throttle = (original, wait, options) => {
282
+ const { leading = true, trailing = true } = options || {};
283
+ return debounce(
284
+ original,
285
+ wait,
286
+ {
287
+ leading,
288
+ trailing,
289
+ throttle: true
290
+ }
291
+ );
292
+ };
293
+
294
+ const flattenDecodeURIComponent = (value) => {
295
+ let need = true;
296
+ let safeCount = 1;
297
+ let parseValue = value;
298
+ while (need) {
299
+ if (safeCount > 1e3) {
300
+ throw new Error(value);
301
+ }
302
+ try {
303
+ let next = decodeURIComponent(parseValue);
304
+ if (parseValue === next) {
305
+ need = false;
306
+ }
307
+ parseValue = next;
308
+ } catch {
309
+ need = false;
310
+ }
311
+ safeCount++;
312
+ }
313
+ return parseValue;
314
+ };
315
+
316
+ const flattenJSONParse = (value) => {
317
+ if (value === null)
318
+ return null;
319
+ let regex = /^\d+$/;
320
+ if (regex.test(value) && value.length >= 16 && +value > Number.MAX_SAFE_INTEGER) {
321
+ return value;
322
+ }
323
+ let need = true;
324
+ let safeCount = 1;
325
+ let parseValue = value;
326
+ while (need) {
327
+ if (safeCount > 10) {
328
+ throw new Error(value);
329
+ }
330
+ try {
331
+ let next = JSON.parse(parseValue);
332
+ if (parseValue === next) {
333
+ need = false;
334
+ }
335
+ parseValue = next;
336
+ } catch {
337
+ need = false;
338
+ }
339
+ safeCount++;
340
+ }
341
+ return parseValue;
342
+ };
343
+
344
+ export { asterisk, autoCatch, canvasToImage, cloneDeepEasier, compressImage, dataURLToFile, debounce, def, flattenDecodeURIComponent, flattenJSONParse, getPropByPath, getUid, hasOwn, isObj, numberToUnit, preZero, probs, raf, range, sleep, throttle };
@@ -0,0 +1,373 @@
1
+ var HelperUtils = (function (exports) {
2
+ 'use strict';
3
+
4
+ const asterisk = (value, from, length) => {
5
+ from = from || 3;
6
+ length = length || 4;
7
+ let repeat = length;
8
+ let content = value.substring(0, from);
9
+ while (repeat) {
10
+ content += "*";
11
+ repeat--;
12
+ }
13
+ content += value.substring(from + length);
14
+ return content;
15
+ };
16
+
17
+ const autoCatch = async (impl, options = {}) => {
18
+ const { onError = console.error } = options;
19
+ let target = impl;
20
+ typeof target === "function" && (target = target());
21
+ try {
22
+ const e = await target;
23
+ return e;
24
+ } catch (e) {
25
+ onError(e);
26
+ }
27
+ };
28
+
29
+ const getMime = (filename) => {
30
+ let ext;
31
+ if (typeof filename === "string" && filename.includes(".")) {
32
+ ext = filename.split(".").pop();
33
+ }
34
+ return ext ? `image/${ext}` : "image/jpeg";
35
+ };
36
+ const dataURLToFile = (dataURL, filename, filetype) => {
37
+ const hasPrefix = /data:[^;]+;[^,]+,/g.test(dataURL);
38
+ if (!hasPrefix) {
39
+ dataURL = `data:${filetype || getMime(filename)};base64,${dataURL}`;
40
+ }
41
+ let [suffix, dataURL$] = dataURL.split(",");
42
+ let mime = suffix.match(/:(.*?);/)?.[1];
43
+ let bstr = window.atob(dataURL$);
44
+ let n = bstr.length;
45
+ let u8arr = new Uint8Array(n);
46
+ while (n--) {
47
+ u8arr[n] = bstr.charCodeAt(n);
48
+ }
49
+ return new File([u8arr], filename || "__filename", { type: mime });
50
+ };
51
+
52
+ const canvasToImage = (canvas, filename) => {
53
+ const dataURL = canvas.toDataURL("image/png");
54
+ return new Promise((resolve) => {
55
+ let result = {
56
+ dataURL
57
+ };
58
+ if (typeof filename === "string") {
59
+ result.file = dataURLToFile(dataURL, filename);
60
+ }
61
+ resolve(result);
62
+ });
63
+ };
64
+
65
+ const cloneDeepEasier = (source) => JSON.parse(JSON.stringify(source));
66
+
67
+ const compressImage = (file, options) => {
68
+ const { width, height, filetype = "image/jpeg", encoderOptions } = options || {};
69
+ return new Promise((resolve, reject) => {
70
+ const el = new Image();
71
+ const reader = new FileReader();
72
+ reader.readAsDataURL(file);
73
+ reader.onload = (e) => {
74
+ el.src = e.target.result;
75
+ };
76
+ const canvas = document.createElement("canvas");
77
+ const context = canvas.getContext("2d");
78
+ el.onload = () => {
79
+ const originWidth = el.width;
80
+ const originHeight = el.height;
81
+ const maxWidth = width || originWidth;
82
+ const maxHeight = height || originHeight;
83
+ let targetWidth = originWidth;
84
+ let targetHeight = originHeight;
85
+ if (originWidth > maxWidth || originHeight > maxHeight) {
86
+ if (originWidth / originHeight > maxWidth / maxHeight) {
87
+ targetWidth = maxWidth;
88
+ targetHeight = Math.round(maxWidth * (originHeight / originWidth));
89
+ } else {
90
+ targetHeight = maxHeight;
91
+ targetWidth = Math.round(maxHeight * (originWidth / originHeight));
92
+ }
93
+ }
94
+ canvas.width = targetWidth;
95
+ canvas.height = targetHeight;
96
+ context.clearRect(0, 0, targetWidth, targetHeight);
97
+ context.drawImage(el, 0, 0, targetWidth, targetHeight);
98
+ const dataURL = canvas.toDataURL(filetype, encoderOptions);
99
+ const compressFile = dataURLToFile(dataURL, file.name);
100
+ resolve({
101
+ dataURL,
102
+ file: compressFile
103
+ });
104
+ };
105
+ el.onerror = (e) => {
106
+ reject(e);
107
+ };
108
+ });
109
+ };
110
+
111
+ const debounce = (original, wait, options) => {
112
+ const { leading, trailing = true, throttle } = options || {};
113
+ let timer;
114
+ let invoke;
115
+ let cancel = () => {
116
+ timer && clearTimeout(timer);
117
+ timer = null;
118
+ };
119
+ let start = () => {
120
+ timer = setTimeout(() => {
121
+ timer = null;
122
+ trailing && invoke && invoke();
123
+ }, wait);
124
+ };
125
+ const fn = function(...args) {
126
+ invoke = () => {
127
+ original.apply(this, args);
128
+ invoke = null;
129
+ };
130
+ if (!wait && throttle)
131
+ return invoke();
132
+ if (!timer) {
133
+ leading && invoke();
134
+ start();
135
+ } else if (!throttle) {
136
+ cancel();
137
+ start();
138
+ }
139
+ };
140
+ fn.cancel = () => {
141
+ cancel();
142
+ invoke = null;
143
+ };
144
+ fn.flush = () => {
145
+ cancel();
146
+ trailing && invoke && invoke();
147
+ };
148
+ return fn;
149
+ };
150
+
151
+ const def = (target, key, value, options) => {
152
+ Object.defineProperty(target, key, {
153
+ value,
154
+ enumerable: false,
155
+ writable: true,
156
+ configurable: true,
157
+ ...options
158
+ });
159
+ };
160
+
161
+ const getPropByPath = (target, path) => {
162
+ let o = target;
163
+ path = path.replace(/\[(\w+)\]/g, ".$1");
164
+ path = path.replace(/^\./, "");
165
+ let keyArr = path.split(".");
166
+ let i = 0;
167
+ for (let len = keyArr.length; i < len - 1; ++i) {
168
+ let key = keyArr[i];
169
+ try {
170
+ if (key in o) {
171
+ o = o[key];
172
+ } else {
173
+ throw new Error();
174
+ }
175
+ } catch {
176
+ throw new Error("无效路径!");
177
+ }
178
+ }
179
+ return {
180
+ o,
181
+ k: keyArr[i],
182
+ v: o[keyArr[i]]
183
+ };
184
+ };
185
+
186
+ const timestamp = +/* @__PURE__ */ new Date();
187
+ let index = 0;
188
+ const getUid = (prefix) => {
189
+ return `${prefix ? `${prefix}-` : ""}${timestamp}-${++index}`;
190
+ };
191
+
192
+ const hasOwn = (target, key) => Object.prototype.hasOwnProperty.call(target, key);
193
+
194
+ const isObj = (target) => typeof target === "object";
195
+
196
+ const getDigit = (integer) => {
197
+ let digit = -1;
198
+ while (integer >= 1) {
199
+ digit++;
200
+ integer /= 10;
201
+ }
202
+ return digit;
203
+ };
204
+ const addWan = (integer, num, mutiple, decimalDigit) => {
205
+ let digit = getDigit(integer);
206
+ if (digit > 3) {
207
+ let remainder = digit % 8;
208
+ if (remainder >= 5) {
209
+ remainder = 4;
210
+ }
211
+ return Math.round(num / Math.pow(10, remainder + mutiple - decimalDigit)) / Math.pow(10, decimalDigit) + "万";
212
+ } else {
213
+ return Math.round(num / Math.pow(10, mutiple - decimalDigit)) / Math.pow(10, decimalDigit) + "";
214
+ }
215
+ };
216
+ const numberToUnit = (number, decimalDigit) => {
217
+ if (number > Number.MAX_SAFE_INTEGER) {
218
+ number = Number.MAX_SAFE_INTEGER;
219
+ }
220
+ decimalDigit = decimalDigit == null ? 2 : decimalDigit;
221
+ let integer = Math.floor(number);
222
+ let digit = getDigit(integer);
223
+ let unit = [];
224
+ if (digit > 3) {
225
+ let multiple = Math.floor(digit / 8);
226
+ if (multiple >= 1) {
227
+ let tmp = Math.round(integer / Math.pow(10, 8 * multiple));
228
+ unit.push(addWan(tmp, number, 8 * multiple, decimalDigit));
229
+ for (let i = 0; i < multiple; i++) {
230
+ unit.push("亿");
231
+ }
232
+ return unit.join("");
233
+ } else {
234
+ return addWan(integer, number, 0, decimalDigit);
235
+ }
236
+ } else {
237
+ return number;
238
+ }
239
+ };
240
+
241
+ const preZero = (num) => {
242
+ if (num < 10 && num > 0) {
243
+ return "0" + num;
244
+ } else if (num <= 0) {
245
+ return "00";
246
+ }
247
+ return "" + num;
248
+ };
249
+
250
+ const raf = typeof window !== "undefined" && window.requestAnimationFrame || ((fn) => setTimeout(fn, 16));
251
+
252
+ const range = (min, max) => {
253
+ return Math.floor(Math.random() * (max - min + 1) + min);
254
+ };
255
+ const probs = (weights) => {
256
+ let sum = weights.reduce((pre, cur) => pre + (!cur || cur <= 0 ? 0 : cur), 0);
257
+ if (!sum) {
258
+ throw new Error("不可能得到索引值");
259
+ }
260
+ let probs$ = weights.map((i) => i / sum);
261
+ let index = 0;
262
+ let r = Math.random();
263
+ while (r > 0) {
264
+ r -= probs$[index];
265
+ index++;
266
+ }
267
+ index--;
268
+ return index;
269
+ };
270
+
271
+ const sleep = (wait, immediate) => {
272
+ let duration;
273
+ if (typeof wait === "object") {
274
+ duration = range(wait.min, wait.max);
275
+ } else {
276
+ duration = wait || 0;
277
+ }
278
+ return new Promise((r) => {
279
+ let timer = setTimeout(r, duration);
280
+ immediate && immediate(timer, duration, r);
281
+ });
282
+ };
283
+
284
+ const throttle = (original, wait, options) => {
285
+ const { leading = true, trailing = true } = options || {};
286
+ return debounce(
287
+ original,
288
+ wait,
289
+ {
290
+ leading,
291
+ trailing,
292
+ throttle: true
293
+ }
294
+ );
295
+ };
296
+
297
+ const flattenDecodeURIComponent = (value) => {
298
+ let need = true;
299
+ let safeCount = 1;
300
+ let parseValue = value;
301
+ while (need) {
302
+ if (safeCount > 1e3) {
303
+ throw new Error(value);
304
+ }
305
+ try {
306
+ let next = decodeURIComponent(parseValue);
307
+ if (parseValue === next) {
308
+ need = false;
309
+ }
310
+ parseValue = next;
311
+ } catch {
312
+ need = false;
313
+ }
314
+ safeCount++;
315
+ }
316
+ return parseValue;
317
+ };
318
+
319
+ const flattenJSONParse = (value) => {
320
+ if (value === null)
321
+ return null;
322
+ let regex = /^\d+$/;
323
+ if (regex.test(value) && value.length >= 16 && +value > Number.MAX_SAFE_INTEGER) {
324
+ return value;
325
+ }
326
+ let need = true;
327
+ let safeCount = 1;
328
+ let parseValue = value;
329
+ while (need) {
330
+ if (safeCount > 10) {
331
+ throw new Error(value);
332
+ }
333
+ try {
334
+ let next = JSON.parse(parseValue);
335
+ if (parseValue === next) {
336
+ need = false;
337
+ }
338
+ parseValue = next;
339
+ } catch {
340
+ need = false;
341
+ }
342
+ safeCount++;
343
+ }
344
+ return parseValue;
345
+ };
346
+
347
+ exports.asterisk = asterisk;
348
+ exports.autoCatch = autoCatch;
349
+ exports.canvasToImage = canvasToImage;
350
+ exports.cloneDeepEasier = cloneDeepEasier;
351
+ exports.compressImage = compressImage;
352
+ exports.dataURLToFile = dataURLToFile;
353
+ exports.debounce = debounce;
354
+ exports.def = def;
355
+ exports.flattenDecodeURIComponent = flattenDecodeURIComponent;
356
+ exports.flattenJSONParse = flattenJSONParse;
357
+ exports.getPropByPath = getPropByPath;
358
+ exports.getUid = getUid;
359
+ exports.hasOwn = hasOwn;
360
+ exports.isObj = isObj;
361
+ exports.numberToUnit = numberToUnit;
362
+ exports.preZero = preZero;
363
+ exports.probs = probs;
364
+ exports.raf = raf;
365
+ exports.range = range;
366
+ exports.sleep = sleep;
367
+ exports.throttle = throttle;
368
+
369
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
370
+
371
+ return exports;
372
+
373
+ })({});