@react-hive/honey-utils 1.4.0 โ 1.6.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/README.md +199 -64
- package/dist/README.md +199 -64
- package/dist/array.d.ts +86 -0
- package/dist/dom.d.ts +44 -4
- package/dist/function.d.ts +99 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.dev.cjs +288 -12
- package/dist/index.dev.cjs.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/README.md
CHANGED
|
@@ -3,10 +3,16 @@
|
|
|
3
3
|
[](https://www.npmjs.com/package/@react-hive/honey-utils)
|
|
4
4
|
[](https://opensource.org/licenses/MIT)
|
|
5
5
|
|
|
6
|
+
<p align="center">
|
|
7
|
+
<img src="./logo.png" alt="honey-utils logo" width="200" height="200">
|
|
8
|
+
</p>
|
|
9
|
+
|
|
6
10
|
A lightweight TypeScript utility library providing a collection of helper functions for common programming tasks.
|
|
7
11
|
|
|
8
12
|
## Features
|
|
9
13
|
|
|
14
|
+
---
|
|
15
|
+
|
|
10
16
|
- ๐ **Type Guards** - Functions for runtime type checking
|
|
11
17
|
- ๐งต **String Utilities** - String manipulation and transformation
|
|
12
18
|
- ๐ข **Array Utilities** - Array filtering and manipulation
|
|
@@ -18,6 +24,8 @@ A lightweight TypeScript utility library providing a collection of helper functi
|
|
|
18
24
|
|
|
19
25
|
## Installation
|
|
20
26
|
|
|
27
|
+
---
|
|
28
|
+
|
|
21
29
|
```bash
|
|
22
30
|
# Using npm
|
|
23
31
|
npm install @react-hive/honey-utils
|
|
@@ -31,9 +39,11 @@ pnpm add @react-hive/honey-utils
|
|
|
31
39
|
|
|
32
40
|
## Usage
|
|
33
41
|
|
|
42
|
+
---
|
|
43
|
+
|
|
34
44
|
### Importing
|
|
35
45
|
|
|
36
|
-
```
|
|
46
|
+
```ts
|
|
37
47
|
// Import specific utilities
|
|
38
48
|
import { toKebabCase, isString, boolFilter } from '@react-hive/honey-utils';
|
|
39
49
|
|
|
@@ -43,7 +53,7 @@ import * as HoneyUtils from '@react-hive/honey-utils';
|
|
|
43
53
|
|
|
44
54
|
### String Utilities
|
|
45
55
|
|
|
46
|
-
```
|
|
56
|
+
```ts
|
|
47
57
|
import { toKebabCase, camelToDashCase, splitStringIntoWords, hashString } from '@react-hive/honey-utils';
|
|
48
58
|
|
|
49
59
|
// Convert string to kebab-case
|
|
@@ -61,35 +71,103 @@ const hash = hashString('background-color: red;'); // 'e4k1z0x'
|
|
|
61
71
|
|
|
62
72
|
### Array Utilities
|
|
63
73
|
|
|
64
|
-
```
|
|
65
|
-
import {
|
|
66
|
-
boolFilter,
|
|
67
|
-
unique,
|
|
68
|
-
chunk,
|
|
69
|
-
intersection,
|
|
70
|
-
difference
|
|
74
|
+
```ts
|
|
75
|
+
import {
|
|
76
|
+
boolFilter,
|
|
77
|
+
unique,
|
|
78
|
+
chunk,
|
|
79
|
+
intersection,
|
|
80
|
+
difference,
|
|
81
|
+
mapAsync,
|
|
82
|
+
forAsync,
|
|
83
|
+
reduceAsync,
|
|
84
|
+
filterAsync,
|
|
85
|
+
someAsync,
|
|
86
|
+
everyAsync,
|
|
87
|
+
findAsync,
|
|
71
88
|
} from '@react-hive/honey-utils';
|
|
72
89
|
|
|
73
90
|
// Filter out falsy values from an array
|
|
74
|
-
boolFilter([0, 1, false, 2, '', 3, null, undefined, true]);
|
|
91
|
+
boolFilter([0, 1, false, 2, '', 3, null, undefined, true]);
|
|
92
|
+
// โ [1, 2, 3, true]
|
|
75
93
|
|
|
76
94
|
// Remove duplicate values from an array
|
|
77
|
-
unique([1, 2, 2, 3, 1, 4]);
|
|
95
|
+
unique([1, 2, 2, 3, 1, 4]);
|
|
96
|
+
// โ [1, 2, 3, 4]
|
|
78
97
|
|
|
79
98
|
// Split an array into chunks of specified size
|
|
80
|
-
chunk([1, 2, 3, 4, 5], 2);
|
|
99
|
+
chunk([1, 2, 3, 4, 5], 2);
|
|
100
|
+
// โ [[1, 2], [3, 4], [5]]
|
|
81
101
|
|
|
82
102
|
// Find common elements between arrays
|
|
83
|
-
intersection([1, 2, 3], [2, 3, 4]);
|
|
103
|
+
intersection([1, 2, 3], [2, 3, 4]);
|
|
104
|
+
// โ [2, 3]
|
|
84
105
|
|
|
85
106
|
// Find elements in one array not in another
|
|
86
|
-
difference([1, 2, 3, 4], [2, 4]);
|
|
107
|
+
difference([1, 2, 3, 4], [2, 4]);
|
|
108
|
+
// โ [1, 3]
|
|
109
|
+
|
|
110
|
+
// Run async operations in parallel and collect results
|
|
111
|
+
await mapAsync([1, 2, 3], async (n) => {
|
|
112
|
+
await delay(100);
|
|
113
|
+
|
|
114
|
+
return n * 2;
|
|
115
|
+
});
|
|
116
|
+
// โ [2, 4, 6]
|
|
117
|
+
|
|
118
|
+
// Run async operations sequentially and collect results
|
|
119
|
+
await forAsync([1, 2, 3], async (n, i) => {
|
|
120
|
+
await delay(100);
|
|
121
|
+
|
|
122
|
+
return n * i;
|
|
123
|
+
});
|
|
124
|
+
// โ [0, 2, 6]
|
|
125
|
+
|
|
126
|
+
// Reduce array asynchronously
|
|
127
|
+
await reduceAsync([1, 2, 3], async (acc, n) => {
|
|
128
|
+
await delay(50);
|
|
129
|
+
|
|
130
|
+
return acc + n;
|
|
131
|
+
}, 0);
|
|
132
|
+
// โ 6
|
|
133
|
+
|
|
134
|
+
// Filter array asynchronously
|
|
135
|
+
await filterAsync([1, 2, 3, 4], async (n) => {
|
|
136
|
+
await delay(30);
|
|
137
|
+
|
|
138
|
+
return n % 2 === 0;
|
|
139
|
+
});
|
|
140
|
+
// โ [2, 4]
|
|
141
|
+
|
|
142
|
+
// Check if some items match condition asynchronously
|
|
143
|
+
await someAsync([1, 3, 5], async (n) => {
|
|
144
|
+
await delay(10);
|
|
145
|
+
|
|
146
|
+
return n % 2 === 0;
|
|
147
|
+
});
|
|
148
|
+
// โ false
|
|
149
|
+
|
|
150
|
+
// Check if all items match condition asynchronously
|
|
151
|
+
await everyAsync([2, 4, 6], async (n) => {
|
|
152
|
+
await delay(10);
|
|
153
|
+
|
|
154
|
+
return n % 2 === 0;
|
|
155
|
+
});
|
|
156
|
+
// โ true
|
|
157
|
+
|
|
158
|
+
// Find first matching item asynchronously
|
|
159
|
+
await findAsync([1, 3, 4, 5], async (n) => {
|
|
160
|
+
await delay(20);
|
|
161
|
+
|
|
162
|
+
return n % 2 === 0;
|
|
163
|
+
});
|
|
164
|
+
// โ 4
|
|
87
165
|
```
|
|
88
166
|
|
|
89
167
|
### Function Utilities
|
|
90
168
|
|
|
91
|
-
```
|
|
92
|
-
import { noop, invokeIfFunction } from '@react-hive/honey-utils';
|
|
169
|
+
```ts
|
|
170
|
+
import { noop, invokeIfFunction, delay, retry } from '@react-hive/honey-utils';
|
|
93
171
|
|
|
94
172
|
// No-operation function
|
|
95
173
|
noop(); // does nothing
|
|
@@ -99,11 +177,38 @@ const fn = (x: number) => x * 2;
|
|
|
99
177
|
|
|
100
178
|
invokeIfFunction(fn, 5); // 10
|
|
101
179
|
invokeIfFunction('not a function', 5); // 'not a function'
|
|
180
|
+
|
|
181
|
+
// Create a promise that resolves after a specified delay
|
|
182
|
+
await delay(1000); // Waits for 1 second before continuing
|
|
183
|
+
|
|
184
|
+
// Retry an async function with configurable options
|
|
185
|
+
async function fetchData() {
|
|
186
|
+
const response = await fetch('/api/data');
|
|
187
|
+
|
|
188
|
+
if (!response.ok) {
|
|
189
|
+
throw new Error('Network error');
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
return await response.json();
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const fetchWithRetry = retry(fetchData, {
|
|
196
|
+
maxAttempts: 5,
|
|
197
|
+
delayMs: 500,
|
|
198
|
+
backoff: true,
|
|
199
|
+
onRetry: (attempt, error) => {
|
|
200
|
+
console.warn(`Attempt ${attempt} failed:`, error);
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
fetchWithRetry()
|
|
205
|
+
.then(data => console.log('Success:', data))
|
|
206
|
+
.catch(error => console.error('Failed after retries:', error));
|
|
102
207
|
```
|
|
103
208
|
|
|
104
209
|
### Type Guards
|
|
105
210
|
|
|
106
|
-
```
|
|
211
|
+
```ts
|
|
107
212
|
import {
|
|
108
213
|
isString,
|
|
109
214
|
isNumber,
|
|
@@ -190,7 +295,7 @@ isSet(new Set()); // true
|
|
|
190
295
|
|
|
191
296
|
### Math Utilities
|
|
192
297
|
|
|
193
|
-
```
|
|
298
|
+
```ts
|
|
194
299
|
import {
|
|
195
300
|
calculateEuclideanDistance,
|
|
196
301
|
calculateMovingSpeed,
|
|
@@ -209,21 +314,37 @@ calculatePercentage(200, 25); // 50
|
|
|
209
314
|
|
|
210
315
|
### DOM Utilities
|
|
211
316
|
|
|
212
|
-
```
|
|
213
|
-
import {
|
|
317
|
+
```ts
|
|
318
|
+
import { parse2DMatrix, cloneBlob, convertBlobToFile } from '@react-hive/honey-utils';
|
|
214
319
|
|
|
215
|
-
//
|
|
320
|
+
// Extract transformation values from an HTML element's 2D matrix
|
|
216
321
|
const element = document.getElementById('my-element');
|
|
217
322
|
if (element) {
|
|
218
|
-
const { translateX, translateY } =
|
|
323
|
+
const { translateX, translateY, scaleX, scaleY, skewX, skewY } = parse2DMatrix(element);
|
|
219
324
|
|
|
220
325
|
console.log(`Element is translated by ${translateX}px horizontally and ${translateY}px vertically`);
|
|
326
|
+
console.log(`Element is scaled by ${scaleX} horizontally and ${scaleY} vertically`);
|
|
327
|
+
console.log(`Element is skewed by ${skewX} horizontally and ${skewY} vertically`);
|
|
221
328
|
}
|
|
329
|
+
|
|
330
|
+
// Clone a Blob object
|
|
331
|
+
const originalBlob = new Blob(['Hello World'], { type: 'text/plain' });
|
|
332
|
+
const clonedBlob = cloneBlob(originalBlob);
|
|
333
|
+
|
|
334
|
+
console.log(clonedBlob.type); // 'text/plain'
|
|
335
|
+
|
|
336
|
+
// Convert a Blob to a File
|
|
337
|
+
const blob = new Blob(['Hello world'], { type: 'text/plain' });
|
|
338
|
+
const file = convertBlobToFile(blob, 'hello.txt');
|
|
339
|
+
|
|
340
|
+
console.log(file instanceof File); // true
|
|
341
|
+
console.log(file.name); // 'hello.txt'
|
|
342
|
+
console.log(file.type); // 'text/plain'
|
|
222
343
|
```
|
|
223
344
|
|
|
224
345
|
### Assert Function
|
|
225
346
|
|
|
226
|
-
```
|
|
347
|
+
```ts
|
|
227
348
|
import { assert } from '@react-hive/honey-utils';
|
|
228
349
|
|
|
229
350
|
// Assert a condition
|
|
@@ -235,64 +356,78 @@ function divide(a: number, b: number): number {
|
|
|
235
356
|
|
|
236
357
|
## API Documentation
|
|
237
358
|
|
|
359
|
+
---
|
|
360
|
+
|
|
238
361
|
### String Utilities
|
|
239
362
|
|
|
240
|
-
-
|
|
241
|
-
-
|
|
242
|
-
-
|
|
243
|
-
-
|
|
363
|
+
- `toKebabCase(input: string): string` - Converts a string to kebab-case.
|
|
364
|
+
- `camelToDashCase(input: string): string` - Converts camelCase to dash-case.
|
|
365
|
+
- `splitStringIntoWords(input: string): string[]` - Splits a string into an array of words.
|
|
366
|
+
- `hashString(input: string): string` - Generates a short hash from a string.
|
|
244
367
|
|
|
245
368
|
### Array Utilities
|
|
246
369
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
-
|
|
250
|
-
-
|
|
251
|
-
-
|
|
370
|
+
#### Synchronous Utilities
|
|
371
|
+
|
|
372
|
+
- `boolFilter<T>(array: (T | false | null | undefined)[]): T[]` - Filters out falsy values (`false`, `null`, `undefined`) from an array while keeping valid items.
|
|
373
|
+
- `unique<T>(array: T[]): T[]` - Returns a new array with all duplicate elements removed. Keeps only the first occurrence of each value.
|
|
374
|
+
- `chunk<T>(array: T[], size: number): T[][]` - Splits an array into smaller arrays ("chunks") of the specified size.
|
|
375
|
+
- `intersection<T>(...arrays: T[][]): T[]` - Returns an array of elements that exist in all provided arrays.
|
|
376
|
+
- `difference<T>(array: T[], exclude: T[]): T[]` - Returns a new array that contains items from `array` that are not present in `exclude`.
|
|
377
|
+
|
|
378
|
+
#### Asynchronous Utilities
|
|
379
|
+
|
|
380
|
+
- `forAsync<Item, Result>(array: Item[], callbackFn: (item, index, array) => Promise<Result>): Promise<Result[]>` - Runs asynchronous operations on each array item *sequentially* and returns the results in the original order.
|
|
381
|
+
- `mapAsync<Item, Return>(array: Item[], callbackFn: (item, index, array) => Promise<Return>): Promise<Return[]>` - Executes an asynchronous function for each array item *in parallel* and returns a promise of all results.
|
|
382
|
+
- `reduceAsync<Item, Accumulator>(array: Item[], callbackFn, initialValue): Promise<Accumulator>` - Asynchronously reduces an array to a single accumulated value. Each step waits for the previous promise to resolve.
|
|
383
|
+
- `filterAsync<Item>(array: Item[], callbackFn): Promise<Item[]>` - Runs an asynchronous filter operation. Only includes items where `callbackFn(item)` resolves to `true`.
|
|
384
|
+
- `someAsync<Item>(array: Item[], callbackFn): Promise<boolean>` - Returns `true` if **any** item in the array passes the async predicate.
|
|
385
|
+
- `everyAsync<Item>(array: Item[], callbackFn): Promise<boolean>` - Returns `true` if **all** items in the array pass the async predicate.
|
|
386
|
+
- `findAsync<Item>(array: Item[], callbackFn): Promise<Item | null>` - Returns the first array item that passes the async predicate, or `null` if no match is found.
|
|
252
387
|
|
|
253
388
|
### Function Utilities
|
|
254
389
|
|
|
255
|
-
-
|
|
256
|
-
-
|
|
390
|
+
- `noop(): void` - A no-operation function.
|
|
391
|
+
- `invokeIfFunction<Args extends any[], Result>(input: ((...args: Args) => Result) | Result, ...args: Args): Result` - Invokes the input if it's a function, otherwise returns it as-is.
|
|
392
|
+
- `delay(delayMs: number): Promise<void>` - Creates a promise that resolves after the specified delay in milliseconds.
|
|
393
|
+
- `retry<Task, TaskResult>(task: Task, options?: RetryOptions): Function` - Wraps an asynchronous function with retry logic, with configurable max attempts, delay between retries, exponential backoff, and retry callbacks.
|
|
257
394
|
|
|
258
395
|
### Type Guards
|
|
259
396
|
|
|
260
|
-
-
|
|
261
|
-
-
|
|
262
|
-
-
|
|
263
|
-
-
|
|
264
|
-
-
|
|
265
|
-
-
|
|
266
|
-
-
|
|
267
|
-
-
|
|
268
|
-
-
|
|
269
|
-
-
|
|
270
|
-
-
|
|
271
|
-
-
|
|
272
|
-
-
|
|
273
|
-
-
|
|
274
|
-
-
|
|
275
|
-
-
|
|
276
|
-
-
|
|
277
|
-
-
|
|
278
|
-
-
|
|
279
|
-
-
|
|
280
|
-
-
|
|
281
|
-
-
|
|
397
|
+
- `assert(condition: any, message: string): asserts condition` - Asserts that a condition is truthy, throwing an error with the provided message if it's not.
|
|
398
|
+
- `isString(value: unknown): value is string` - Checks if a value is a string.
|
|
399
|
+
- `isNumber(value: unknown): value is number` - Checks if a value is a number.
|
|
400
|
+
- `isBool(value: unknown): value is boolean` - Checks if a value is a boolean.
|
|
401
|
+
- `isObject(value: unknown): value is object` - Checks if a value is an object.
|
|
402
|
+
- `isFunction(value: unknown): value is Function` - Checks if a value is a function.
|
|
403
|
+
- `isPromise<T = unknown>(value: unknown): value is Promise<T>` - Checks if a value is a Promise.
|
|
404
|
+
- `isNil(value: unknown): value is null | undefined` - Checks if a value is null or undefined.
|
|
405
|
+
- `isNilOrEmptyString(value: unknown): value is null | undefined` - Checks if a value is null, undefined, or an empty string.
|
|
406
|
+
- `isArray(value: unknown): value is unknown[]` - Checks if a value is an array.
|
|
407
|
+
- `isEmptyArray(value: unknown): value is []` - Checks if a value is an empty array.
|
|
408
|
+
- `isEmptyObject(value: unknown): value is Record<string, never>` - Checks if a value is an empty object.
|
|
409
|
+
- `isNull(value: unknown): value is null` - Checks if a value is null.
|
|
410
|
+
- `isUndefined(value: unknown): value is undefined` - Checks if a value is undefined.
|
|
411
|
+
- `isFiniteNumber(value: unknown): value is number` - Checks if a value is a finite number.
|
|
412
|
+
- `isInteger(value: unknown): value is number` - Checks if a value is an integer.
|
|
413
|
+
- `isDate(value: unknown): value is Date` - Checks if a value is a Date object.
|
|
414
|
+
- `isValidDate(value: unknown): value is Date` - Checks if a value is a valid Date object (not Invalid Date).
|
|
415
|
+
- `isRegExp(value: unknown): value is RegExp` - Checks if a value is a RegExp object.
|
|
416
|
+
- `isMap(value: unknown): value is Map<unknown, unknown>` - Checks if a value is a Map.
|
|
417
|
+
- `isSet(value: unknown): value is Set<unknown>` - Checks if a value is a Set.
|
|
418
|
+
- `isSymbol(value: unknown): value is symbol` - Checks if a value is a Symbol.
|
|
282
419
|
|
|
283
420
|
### Math Utilities
|
|
284
421
|
|
|
285
|
-
-
|
|
286
|
-
-
|
|
287
|
-
-
|
|
422
|
+
- `calculateEuclideanDistance(startX: number, startY: number, endX: number, endY: number): number` - Calculates the Euclidean distance between two points.
|
|
423
|
+
- `calculateMovingSpeed(delta: number, elapsedTime: number): number` - Calculates moving speed.
|
|
424
|
+
- `calculatePercentage(value: number, percentage: number): number` - Calculates the specified percentage of a value.
|
|
288
425
|
|
|
289
426
|
### DOM Utilities
|
|
290
427
|
|
|
291
|
-
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
- **assert(condition: any, message: string): asserts condition** - Asserts that a condition is truthy, throwing an error with the provided message if it's not
|
|
428
|
+
- `parse2DMatrix(element: HTMLElement): { translateX: number, translateY: number, scaleX: number, scaleY: number, skewX: number, skewY: number }` - Extracts transformation values (translate, scale, skew) from the 2D transformation matrix of a given HTML element.
|
|
429
|
+
- `cloneBlob(blob: Blob): Blob` - Creates a clone of a Blob object with the same content and type as the original.
|
|
430
|
+
- `convertBlobToFile(blob: Blob, fileName: string): File` - Converts a Blob object into a File object with the specified name.
|
|
296
431
|
|
|
297
432
|
## Contributing
|
|
298
433
|
|
package/dist/array.d.ts
CHANGED
|
@@ -82,3 +82,89 @@ export declare const intersection: <T>(...arrays: T[][]) => T[];
|
|
|
82
82
|
* ```
|
|
83
83
|
*/
|
|
84
84
|
export declare const difference: <T>(array: T[], exclude: T[]) => T[];
|
|
85
|
+
/**
|
|
86
|
+
* Asynchronously iterates over an array and executes an async function on each item sequentially,
|
|
87
|
+
* collecting the results.
|
|
88
|
+
*
|
|
89
|
+
* Unlike `Promise.all`, this runs each promise one after another (not in parallel).
|
|
90
|
+
* Useful when order or timing matters (e.g., rate limits, UI updates, animations).
|
|
91
|
+
*
|
|
92
|
+
* @param array - The array of items to iterate over.
|
|
93
|
+
* @param callbackFn - An async function to execute for each item. Must return a value.
|
|
94
|
+
*
|
|
95
|
+
* @returns A promise that resolves with an array of results from each callback call.
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* ```ts
|
|
99
|
+
* const results = await forAsync([1, 2, 3], async (item) => {
|
|
100
|
+
* await delay(100);
|
|
101
|
+
*
|
|
102
|
+
* return item * 2;
|
|
103
|
+
* });
|
|
104
|
+
*
|
|
105
|
+
* console.log(results); // [2, 4, 6]
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
108
|
+
export declare const forAsync: <Item, Result>(array: Item[], callbackFn: (item: Item, index: number, array: Item[]) => Promise<Result>) => Promise<Result[]>;
|
|
109
|
+
/**
|
|
110
|
+
* Executes an asynchronous operation on each element of an array and waits for all promises to resolve.
|
|
111
|
+
*
|
|
112
|
+
* @param array - The array of items to operate on.
|
|
113
|
+
* @param callbackFn - The asynchronous operation to perform on each item.
|
|
114
|
+
*
|
|
115
|
+
* @returns A promise that resolves with an array of results after all operations are completed.
|
|
116
|
+
*/
|
|
117
|
+
export declare const mapAsync: <Item, Return>(array: Item[], callbackFn: (item: Item, index: number, array: Item[]) => Promise<Return>) => Promise<Return[]>;
|
|
118
|
+
/**
|
|
119
|
+
* A generic function that processes an array asynchronously and filters the results
|
|
120
|
+
* based on the provided async condition.
|
|
121
|
+
*
|
|
122
|
+
* @template Item - The type of the items in the array.
|
|
123
|
+
* @template Return - The type of the items returned by the condition.
|
|
124
|
+
*
|
|
125
|
+
* @param array - An array of items to be processed.
|
|
126
|
+
* @param callbackFn - An async function that returns a condition for each item.
|
|
127
|
+
*
|
|
128
|
+
* @returns A Promise that resolves to an array of items that match the condition.
|
|
129
|
+
*/
|
|
130
|
+
export declare const filterAsync: <Item>(array: Item[], callbackFn: (item: Item, index: number, array: Item[]) => Promise<boolean>) => Promise<Item[]>;
|
|
131
|
+
/**
|
|
132
|
+
* Asynchronously checks if at least one element in the array satisfies the async condition.
|
|
133
|
+
*
|
|
134
|
+
* @param array - The array of items to check.
|
|
135
|
+
* @param callbackFn - An async function that returns a boolean.
|
|
136
|
+
*
|
|
137
|
+
* @returns A promise that resolves to true if any item passes the condition.
|
|
138
|
+
*/
|
|
139
|
+
export declare const someAsync: <Item>(array: Item[], callbackFn: (item: Item, index: number, array: Item[]) => Promise<boolean>) => Promise<boolean>;
|
|
140
|
+
/**
|
|
141
|
+
* Asynchronously checks if all elements in the array satisfy the async condition.
|
|
142
|
+
*
|
|
143
|
+
* @param array - The array of items to check.
|
|
144
|
+
* @param callbackFn - An async function that returns a boolean.
|
|
145
|
+
*
|
|
146
|
+
* @returns A promise that resolves to true if all items pass the condition.
|
|
147
|
+
*/
|
|
148
|
+
export declare const everyAsync: <Item>(array: Item[], callbackFn: (item: Item, index: number, array: Item[]) => Promise<boolean>) => Promise<boolean>;
|
|
149
|
+
/**
|
|
150
|
+
* Asynchronously reduces an array to a single accumulated value.
|
|
151
|
+
*
|
|
152
|
+
* @template Item - The type of items in the array.
|
|
153
|
+
* @template Accumulator - The type of the accumulated result.
|
|
154
|
+
*
|
|
155
|
+
* @param array - The array to reduce.
|
|
156
|
+
* @param callbackFn - The async reducer function that processes each item and returns the updated accumulator.
|
|
157
|
+
* @param initialValue - The initial accumulator value.
|
|
158
|
+
*
|
|
159
|
+
* @returns A promise that resolves to the final accumulated result.
|
|
160
|
+
*/
|
|
161
|
+
export declare const reduceAsync: <Item, Accumulator>(array: Item[], callbackFn: (accumulator: Accumulator, item: Item, index: number, array: Item[]) => Promise<Accumulator>, initialValue: Accumulator) => Promise<Accumulator>;
|
|
162
|
+
/**
|
|
163
|
+
* Asynchronously finds the first element that satisfies the async condition.
|
|
164
|
+
*
|
|
165
|
+
* @param array - The array of items to search.
|
|
166
|
+
* @param callbackFn - An async function that returns a boolean.
|
|
167
|
+
*
|
|
168
|
+
* @returns A promise that resolves to the found item or null if none match.
|
|
169
|
+
*/
|
|
170
|
+
export declare const findAsync: <Item>(array: Item[], callbackFn: (item: Item, index: number, array: Item[]) => Promise<boolean>) => Promise<Item | null>;
|
package/dist/dom.d.ts
CHANGED
|
@@ -1,13 +1,53 @@
|
|
|
1
1
|
interface HTMLElementTransformationValues {
|
|
2
2
|
translateX: number;
|
|
3
3
|
translateY: number;
|
|
4
|
+
scaleX: number;
|
|
5
|
+
scaleY: number;
|
|
6
|
+
skewX: number;
|
|
7
|
+
skewY: number;
|
|
4
8
|
}
|
|
5
9
|
/**
|
|
6
|
-
*
|
|
10
|
+
* Extracts transformation values (translate, scale, skew) from the 2D transformation matrix of a given HTML element.
|
|
7
11
|
*
|
|
8
|
-
*
|
|
12
|
+
* Only works with 2D transforms (i.e., `matrix(a, b, c, d, e, f)`).
|
|
9
13
|
*
|
|
10
|
-
* @
|
|
14
|
+
* @param element - The element with a CSS transform applied.
|
|
15
|
+
* @returns An object with parsed transformation values.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* const values = parse2DMatrix(myElement);
|
|
20
|
+
* console.log(values.translateX);
|
|
21
|
+
* console.log(values.scaleX);
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export declare const parse2DMatrix: (element: HTMLElement) => HTMLElementTransformationValues;
|
|
25
|
+
/**
|
|
26
|
+
* Creates a clone of a Blob object.
|
|
27
|
+
*
|
|
28
|
+
* @param blob - The Blob object to clone.
|
|
29
|
+
*
|
|
30
|
+
* @returns A new Blob with the same content and type as the original.
|
|
31
|
+
*/
|
|
32
|
+
export declare const cloneBlob: (blob: Blob) => Blob;
|
|
33
|
+
/**
|
|
34
|
+
* Converts a `Blob` object into a `File` object with the specified name.
|
|
35
|
+
*
|
|
36
|
+
* This is useful when you receive a `Blob` (e.g., from canvas, fetch, or file manipulation)
|
|
37
|
+
* and need to convert it into a `File` to upload via `FormData` or file inputs.
|
|
38
|
+
*
|
|
39
|
+
* @param blob - The `Blob` to convert.
|
|
40
|
+
* @param fileName - The desired name for the resulting file (including extension).
|
|
41
|
+
*
|
|
42
|
+
* @returns A `File` instance with the same content and MIME type as the input `Blob`.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```ts
|
|
46
|
+
* const blob = new Blob(['Hello world'], { type: 'text/plain' });
|
|
47
|
+
* const file = convertBlobToFile(blob, 'hello.txt');
|
|
48
|
+
*
|
|
49
|
+
* console.log(file instanceof File); // true
|
|
50
|
+
* ```
|
|
11
51
|
*/
|
|
12
|
-
export declare const
|
|
52
|
+
export declare const convertBlobToFile: (blob: Blob, fileName: string) => File;
|
|
13
53
|
export {};
|
package/dist/function.d.ts
CHANGED
|
@@ -11,4 +11,102 @@ export declare const noop: () => void;
|
|
|
11
11
|
*
|
|
12
12
|
* @returns The result of invoking the function, or the original value if it's not a function.
|
|
13
13
|
*/
|
|
14
|
-
export declare const invokeIfFunction: <Args extends
|
|
14
|
+
export declare const invokeIfFunction: <Args extends unknown[], Result>(input: ((...args: Args) => Result) | Result, ...args: Args) => Result;
|
|
15
|
+
/**
|
|
16
|
+
* Creates a promise that resolves after the specified delay.
|
|
17
|
+
*
|
|
18
|
+
* Useful for creating artificial delays, implementing timeouts, or spacing operations.
|
|
19
|
+
*
|
|
20
|
+
* @param delayMs - The delay in milliseconds.
|
|
21
|
+
*
|
|
22
|
+
* @returns A promise that resolves after the specified delay.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```ts
|
|
26
|
+
* // Wait for 1 second
|
|
27
|
+
* await delay(1000);
|
|
28
|
+
* console.log('This logs after 1 second');
|
|
29
|
+
*
|
|
30
|
+
* // Use with other async operations
|
|
31
|
+
* async function fetchWithTimeout() {
|
|
32
|
+
* const timeoutPromise = delay(5000).then(() => {
|
|
33
|
+
* throw new Error('Request timed out');
|
|
34
|
+
* });
|
|
35
|
+
*
|
|
36
|
+
* return Promise.race([fetchData(), timeoutPromise]);
|
|
37
|
+
* }
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export declare const delay: (delayMs: number) => Promise<void>;
|
|
41
|
+
interface RetryOptions {
|
|
42
|
+
/**
|
|
43
|
+
* Maximum number of retry attempts before failing.
|
|
44
|
+
*
|
|
45
|
+
* @default 3
|
|
46
|
+
*/
|
|
47
|
+
maxAttempts?: number;
|
|
48
|
+
/**
|
|
49
|
+
* Delay in milliseconds between retry attempts.
|
|
50
|
+
* If `backoff` is true, this is the base delay for exponential backoff.
|
|
51
|
+
*
|
|
52
|
+
* @default 300
|
|
53
|
+
*/
|
|
54
|
+
delayMs?: number;
|
|
55
|
+
/**
|
|
56
|
+
* Whether to use exponential backoff for delays between attempts.
|
|
57
|
+
* When enabled, the delay is multiplied by 2 ^ (`attempt` - 1).
|
|
58
|
+
*
|
|
59
|
+
* @default true
|
|
60
|
+
*/
|
|
61
|
+
backoff?: boolean;
|
|
62
|
+
/**
|
|
63
|
+
* Optional callback triggered before each retry attempt.
|
|
64
|
+
*
|
|
65
|
+
* @param attempt - The current attempt number (starting from 1).
|
|
66
|
+
* @param error - The error that caused the retry.
|
|
67
|
+
*/
|
|
68
|
+
onRetry?: (attempt: number, error: unknown) => void;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Wraps an asynchronous function with retry logic.
|
|
72
|
+
*
|
|
73
|
+
* The returned function will attempt to call the original function up to `maxAttempts` times,
|
|
74
|
+
* with a delay between retries. If all attempts fail, the last encountered error is thrown.
|
|
75
|
+
*
|
|
76
|
+
* Useful for operations that may fail intermittently, such as network requests.
|
|
77
|
+
*
|
|
78
|
+
* @template Task - The type of the async function to wrap.
|
|
79
|
+
* @template TaskResult - The result type of the async function.
|
|
80
|
+
*
|
|
81
|
+
* @param task - The async function to wrap with retry logic.
|
|
82
|
+
* @param options - Configuration options for retry behavior.
|
|
83
|
+
*
|
|
84
|
+
* @returns A function that wraps the original function with retry support.
|
|
85
|
+
*
|
|
86
|
+
* @example
|
|
87
|
+
* ```ts
|
|
88
|
+
* async function fetchData() {
|
|
89
|
+
* const response = await fetch('/api/data');
|
|
90
|
+
*
|
|
91
|
+
* if (!response.ok) {
|
|
92
|
+
* throw new Error('Network error');
|
|
93
|
+
* }
|
|
94
|
+
*
|
|
95
|
+
* return await response.json();
|
|
96
|
+
* }
|
|
97
|
+
*
|
|
98
|
+
* const fetchWithRetry = retry(fetchData, {
|
|
99
|
+
* maxAttempts: 5,
|
|
100
|
+
* delayMs: 500,
|
|
101
|
+
* onRetry: (attempt, error) => {
|
|
102
|
+
* console.warn(`Attempt ${attempt} failed:`, error);
|
|
103
|
+
* }
|
|
104
|
+
* });
|
|
105
|
+
*
|
|
106
|
+
* fetchWithRetry()
|
|
107
|
+
* .then(data => console.log('Success:', data))
|
|
108
|
+
* .catch(error => console.error('Failed after retries:', error));
|
|
109
|
+
* ```
|
|
110
|
+
*/
|
|
111
|
+
export declare const retry: <Task extends (...args: unknown[]) => Promise<TaskResult>, TaskResult>(task: Task, { maxAttempts, delayMs, backoff, onRetry }?: RetryOptions) => ((...args: Parameters<Task>) => Promise<TaskResult>);
|
|
112
|
+
export {};
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(()=>{"use strict";var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{assert:()=>
|
|
1
|
+
(()=>{"use strict";var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{assert:()=>i,boolFilter:()=>C,calculateEuclideanDistance:()=>V,calculateMovingSpeed:()=>Z,calculatePercentage:()=>_,camelToDashCase:()=>n,chunk:()=>N,cloneBlob:()=>U,convertBlobToFile:()=>W,delay:()=>q,difference:()=>x,everyAsync:()=>Y,filterAsync:()=>T,findAsync:()=>$,forAsync:()=>B,hashString:()=>s,intersection:()=>E,invokeIfFunction:()=>R,isArray:()=>p,isBool:()=>y,isDate:()=>w,isEmptyArray:()=>g,isEmptyObject:()=>f,isFiniteNumber:()=>P,isFunction:()=>m,isInteger:()=>j,isMap:()=>v,isNil:()=>b,isNilOrEmptyString:()=>d,isNull:()=>o,isNumber:()=>c,isObject:()=>u,isPromise:()=>h,isRegExp:()=>S,isSet:()=>M,isString:()=>l,isSymbol:()=>k,isUndefined:()=>O,isValidDate:()=>A,mapAsync:()=>D,noop:()=>L,parse2DMatrix:()=>K,reduceAsync:()=>I,retry:()=>z,someAsync:()=>X,splitStringIntoWords:()=>a,toKebabCase:()=>r,unique:()=>F});const r=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),n=e=>{const t=e.charAt(0),r=e.slice(1);return t.toLowerCase()+r.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)},a=e=>e.split(" ").filter(Boolean),s=e=>{let t=5381;for(let r=0;r<e.length;r++)t=33*t^e.charCodeAt(r);return(t>>>0).toString(36)};function i(e,t){if(!e)throw new Error(t)}const o=e=>null===e,l=e=>"string"==typeof e,c=e=>"number"==typeof e,y=e=>"boolean"==typeof e,u=e=>"object"==typeof e,f=e=>u(e)&&!o(e)&&0===Object.keys(e).length,p=e=>Array.isArray(e),g=e=>p(e)&&0===e.length,m=e=>"function"==typeof e,h=e=>m(e?.then),b=e=>null==e,d=e=>""===e||b(e),w=e=>e instanceof Date,A=e=>w(e)&&!isNaN(e.getTime()),S=e=>e instanceof RegExp,v=e=>e instanceof Map,M=e=>e instanceof Set,k=e=>"symbol"==typeof e,O=e=>void 0===e,P=e=>c(e)&&isFinite(e),j=e=>c(e)&&Number.isInteger(e),C=e=>e.filter(Boolean),F=e=>[...new Set(e)],N=(e,t)=>(i(t>0,"Chunk size must be greater than 0"),Array.from({length:Math.ceil(e.length/t)},(r,n)=>e.slice(n*t,(n+1)*t))),E=(...e)=>{if(0===e.length)return[];if(1===e.length)return[...e[0]];const[t,...r]=e;return F(t).filter(e=>r.every(t=>t.includes(e)))},x=(e,t)=>e.filter(e=>!t.includes(e)),B=async(e,t)=>{const r=[];for(let n=0;n<e.length;n++)r.push(await t(e[n],n,e));return r},D=async(e,t)=>Promise.all(e.map(t)),T=async(e,t)=>{const r=await D(e,async(e,r,n)=>!!await t(e,r,n)&&e);return C(r)},X=async(e,t)=>{for(let r=0;r<e.length;r++)if(await t(e[r],r,e))return!0;return!1},Y=async(e,t)=>{for(let r=0;r<e.length;r++)if(!await t(e[r],r,e))return!1;return!0},I=async(e,t,r)=>{let n=r;for(let r=0;r<e.length;r++)n=await t(n,e[r],r,e);return n},$=async(e,t)=>{for(let r=0;r<e.length;r++)if(await t(e[r],r,e))return e[r];return null},L=()=>{},R=(e,...t)=>"function"==typeof e?e(...t):e,q=e=>new Promise(t=>setTimeout(t,e)),z=(e,{maxAttempts:t=3,delayMs:r=300,backoff:n=!0,onRetry:a}={})=>async(...s)=>{let i;for(let o=1;o<=t;o++)try{return await e(...s)}catch(e){if(i=e,o<t){a?.(o,e);const t=n?r*2**(o-1):r;await q(t)}}throw i},V=(e,t,r,n)=>{const a=r-e,s=n-t;return Math.sqrt(a**2+s**2)},Z=(e,t)=>Math.abs(e/t),_=(e,t)=>e*t/100,K=e=>{const t=window.getComputedStyle(e).getPropertyValue("transform").match(/^matrix\((.+)\)$/);if(!t)return{translateX:0,translateY:0,scaleX:1,scaleY:1,skewX:0,skewY:0};const[r,n,a,s,i,o]=t[1].split(", ").map(parseFloat);return{translateX:i,translateY:o,scaleX:r,scaleY:s,skewX:a,skewY:n}},U=e=>new Blob([e],{type:e.type}),W=(e,t)=>new File([e],t,{type:e.type});module.exports=t})();
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|