@superutils/core 1.0.6 → 1.1.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 +21 -17
- package/dist/index.d.ts +35 -23
- package/dist/index.js +13 -20
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ For full API reference check out the [docs page](https://alien45.github.io/super
|
|
|
15
15
|
- [`is`](#is): Type checkers
|
|
16
16
|
- [`deferred()`](#deferred): Debounce callbacks
|
|
17
17
|
- [`throttle()`](#throttle): Throttle callbacks
|
|
18
|
-
- [`fallbackIfFails()`](#fallback-if-fails): Gracefully invoke functions
|
|
18
|
+
- [`fallbackIfFails()`](#fallback-if-fails): Gracefully invoke functions or promises with a fallback
|
|
19
19
|
- [`objCopy()`](#obj-copy): Deep-copy objects
|
|
20
20
|
- [`search()`](#search): Search iterable collections
|
|
21
21
|
|
|
@@ -53,8 +53,7 @@ is.map(new Map()) // true
|
|
|
53
53
|
is.number(123) // true
|
|
54
54
|
is.number(NaN) // false
|
|
55
55
|
is.url('https://google.com') // true
|
|
56
|
-
|
|
57
|
-
|
|
56
|
+
//...
|
|
58
57
|
```
|
|
59
58
|
|
|
60
59
|
All these functions can also be imported independantly.
|
|
@@ -80,16 +79,15 @@ import {
|
|
|
80
79
|
`debounce()`, a sugar for `deferred()`, is also available.
|
|
81
80
|
|
|
82
81
|
```javascript
|
|
83
|
-
|
|
84
82
|
import { deferred } from '@superutils/core'
|
|
85
83
|
|
|
86
84
|
const handleChange = deferred(
|
|
87
|
-
|
|
88
|
-
|
|
85
|
+
event => console.log(event.target.value),
|
|
86
|
+
300, // debounce delay in milliseconds
|
|
89
87
|
)
|
|
90
|
-
handleChange({ target: { value 1 } }) // will be ignored
|
|
91
|
-
handleChange({ target: { value 2 } }) // will be ignored
|
|
92
|
-
handleChange({ target: { value 3 } }) // will be executed
|
|
88
|
+
handleChange({ target: { value: 1 } }) // will be ignored
|
|
89
|
+
handleChange({ target: { value: 2 } }) // will be ignored
|
|
90
|
+
handleChange({ target: { value: 3 } }) // will be executed
|
|
93
91
|
```
|
|
94
92
|
|
|
95
93
|
<div id="throttle"></div>
|
|
@@ -100,19 +98,19 @@ handleChange({ target: { value 3 } }) // will be executed
|
|
|
100
98
|
import { throttle } from '@superutils/core'
|
|
101
99
|
|
|
102
100
|
const handleChange = throttle(
|
|
103
|
-
|
|
104
|
-
|
|
101
|
+
event => console.log(event.target.value),
|
|
102
|
+
300, // throttle duration in milliseconds
|
|
105
103
|
)
|
|
106
|
-
handleChange({ target: { value 1 } }) // will be executed
|
|
107
|
-
handleChange({ target: { value 2 } }) // will be ignored
|
|
108
|
-
handleChange({ target: { value 3 } }) // will be ignored
|
|
104
|
+
handleChange({ target: { value: 1 } }) // will be executed
|
|
105
|
+
handleChange({ target: { value: 2 } }) // will be ignored
|
|
106
|
+
handleChange({ target: { value: 3 } }) // will be ignored
|
|
109
107
|
```
|
|
110
108
|
|
|
111
109
|
<div id="fallback-if-fails"></div>
|
|
112
110
|
|
|
113
|
-
### `fallbackIfFails(
|
|
111
|
+
### `fallbackIfFails(target, args, fallback)`: Gracefully invoke functions or promises with a fallback
|
|
114
112
|
|
|
115
|
-
|
|
113
|
+
The `fallbackIfFails` function can wrap a standard function, a promise-returning function, or a promise directly. It automatically handles both synchronous execution and asynchronous resolution, providing a fallback value if the function throws an error or the promise is rejected.
|
|
116
114
|
|
|
117
115
|
#### Sync operations:
|
|
118
116
|
|
|
@@ -149,6 +147,12 @@ fallbackIfFails(
|
|
|
149
147
|
{ products: [] }, // Fallback value to be returned when function throws an error.
|
|
150
148
|
).then(console.log)
|
|
151
149
|
// Prints the result when request is successful or fallback value when request fails
|
|
150
|
+
|
|
151
|
+
// use a promise
|
|
152
|
+
fallbackIfFails(
|
|
153
|
+
Promise.reject('error'),
|
|
154
|
+
[], //
|
|
155
|
+
)
|
|
152
156
|
```
|
|
153
157
|
|
|
154
158
|
<div id="obj-copy"></div>
|
|
@@ -249,7 +253,7 @@ search(data, {
|
|
|
249
253
|
asMap: false, // Result type: true => Map (default, keys preserved), false => Array
|
|
250
254
|
ignoreCase: false, // For text case-sensitivity
|
|
251
255
|
limit: 10, // Number of items returned. Default: no limit
|
|
252
|
-
matchExact: true, // true:
|
|
256
|
+
matchExact: true, // true: match exact value. false (default): partial matching
|
|
253
257
|
matchAll: true, // if true, item will be matched only when all of the query properties match
|
|
254
258
|
query: {
|
|
255
259
|
age: /(2[5-9])|(3[0-5])/, // match ages 25-35
|
package/dist/index.d.ts
CHANGED
|
@@ -24,15 +24,19 @@ type CreateTuple<T, Length extends number, Output extends readonly unknown[] = [
|
|
|
24
24
|
* @template TData The final return type.
|
|
25
25
|
*/
|
|
26
26
|
type Curry<TData, TParams extends unknown[]> = <TArgs extends unknown[]>(...args: TArgs & KeepFirstN<TParams, TArgs['length']>) => DropFirstN<TParams, TArgs['length']> extends [unknown, ...unknown[]] ? Curry<TData, DropFirstN<TParams, TArgs['length']>> : TData;
|
|
27
|
+
type CurriedArgs<TArgs extends unknown[], TArgsIsFinite extends boolean, TFunc extends (...args: any[]) => unknown, TArity extends number> = TArgsIsFinite extends false ? CreateTuple<Parameters<TFunc>[number], TArity> : KeepFirstN<[
|
|
28
|
+
...KeepRequired<TArgs>,
|
|
29
|
+
...KeepOptionals<TArgs, true, undefined>
|
|
30
|
+
], TArity>;
|
|
27
31
|
/**
|
|
28
|
-
* Deferred function
|
|
32
|
+
* Deferred function options
|
|
29
33
|
*/
|
|
30
|
-
|
|
34
|
+
type DeferredOptions<ThisArg = unknown> = {
|
|
31
35
|
leading?: boolean | 'global';
|
|
32
36
|
onError?: (err: unknown) => ValueOrPromise<unknown>;
|
|
33
37
|
thisArg?: ThisArg;
|
|
34
38
|
tid?: TimeoutId;
|
|
35
|
-
}
|
|
39
|
+
};
|
|
36
40
|
/**
|
|
37
41
|
* Drop the first item from an array/tuple and keep the rest
|
|
38
42
|
* ---
|
|
@@ -249,14 +253,10 @@ type ValueOrPromise<T> = T | Promise<T>;
|
|
|
249
253
|
declare function curry<TData, TArgs extends unknown[], TArgsIsFinite extends boolean = IsFiniteTuple<TArgs>, TArity extends TArgs['length'] = TArgsIsFinite extends true ? TupleMaxLength<TArgs> : number>(func: (...args: TArgs) => TData, ...[arity]: TArgsIsFinite extends true ? [arity?: TArity] : [
|
|
250
254
|
arity: TArity
|
|
251
255
|
]): Curry<TData, CurriedArgs<TArgs, TArgsIsFinite, (...args: TArgs) => TData, TArity>>;
|
|
252
|
-
type CurriedArgs<TArgs extends unknown[], TArgsIsFinite extends boolean, TFunc extends (...args: any[]) => unknown, TArity extends number> = TArgsIsFinite extends false ? CreateTuple<Parameters<TFunc>[number], TArity> : KeepFirstN<[
|
|
253
|
-
...KeepRequired<TArgs>,
|
|
254
|
-
...KeepOptionals<TArgs, true, undefined>
|
|
255
|
-
], TArity>;
|
|
256
256
|
|
|
257
257
|
/**
|
|
258
|
-
*
|
|
259
|
-
*
|
|
258
|
+
*
|
|
259
|
+
* Returns a function that invokes the callback function after certain delay/timeout.
|
|
260
260
|
* All errors will be gracefully swallowed.
|
|
261
261
|
*
|
|
262
262
|
* @param callback function to be invoked after timeout
|
|
@@ -267,20 +267,18 @@ type CurriedArgs<TArgs extends unknown[], TArgsIsFinite extends boolean, TFunc e
|
|
|
267
267
|
* @param config.tid (optional) Timeout Id. If provided, will clear the timeout on first invocation.
|
|
268
268
|
*
|
|
269
269
|
* @example Debounce function calls
|
|
270
|
-
* ```
|
|
270
|
+
* ```javascript
|
|
271
271
|
* import { deferred } from '@superutils/core'
|
|
272
272
|
*
|
|
273
273
|
* const handleChange = deferred(
|
|
274
|
-
* event => console.log(event.target.value),
|
|
274
|
+
* event => console.log('Value:', event.target.value),
|
|
275
275
|
* 300 // debounce delay in milliseconds
|
|
276
276
|
* )
|
|
277
277
|
*
|
|
278
|
-
* handleChange({ target: { value 1 } }) // will be ignored
|
|
279
|
-
* handleChange({ target: { value 2 } }) // will be ingored
|
|
280
|
-
* handleChange({ target: { value 3 } }) // will be invoked
|
|
278
|
+
* handleChange({ target: { value: 1 } }) // will be ignored
|
|
279
|
+
* handleChange({ target: { value: 2 } }) // will be ingored
|
|
280
|
+
* handleChange({ target: { value: 3 } }) // will be invoked
|
|
281
281
|
* ```
|
|
282
|
-
*
|
|
283
|
-
*
|
|
284
282
|
*/
|
|
285
283
|
declare const deferred: {
|
|
286
284
|
<TArgs extends unknown[], ThisArg>(callback: (this: ThisArg, ...args: TArgs) => ValueOrPromise<unknown>, delay?: number, config?: DeferredOptions<ThisArg>): (...args: TArgs) => void;
|
|
@@ -299,7 +297,13 @@ declare const deferred: {
|
|
|
299
297
|
};
|
|
300
298
|
|
|
301
299
|
/** Super for `deferred()` function */
|
|
302
|
-
declare
|
|
300
|
+
declare const debounce: {
|
|
301
|
+
<TArgs extends unknown[], ThisArg>(callback: (this: ThisArg, ...args: TArgs) => ValueOrPromise<unknown>, delay?: number, config?: DeferredOptions<ThisArg>): (...args: TArgs) => void;
|
|
302
|
+
defaults: {
|
|
303
|
+
leading: false;
|
|
304
|
+
onError: undefined;
|
|
305
|
+
};
|
|
306
|
+
};
|
|
303
307
|
|
|
304
308
|
/**
|
|
305
309
|
* If `T` is a promise turn it into an union type by adding the value type
|
|
@@ -381,11 +385,6 @@ type IfPromiseAddValue<T> = T extends Promise<infer V> ? T | V : T;
|
|
|
381
385
|
*/
|
|
382
386
|
declare const fallbackIfFails: <T, TArgs extends unknown[] = unknown[]>(target: T | ((...args: TArgs) => T), args: TArgs | (() => TArgs), fallbackValue: IfPromiseAddValue<T> | ((reason: unknown) => IfPromiseAddValue<T>)) => T;
|
|
383
387
|
|
|
384
|
-
/** Cast a value as `any` type to bypass type check. Use with caution. */
|
|
385
|
-
declare const asAny: <T = any>(x: unknown) => T;
|
|
386
|
-
/** Force cast one type into another to bypass type checks. Use with caution. */
|
|
387
|
-
declare const forceCast: <T>(x: unknown) => T;
|
|
388
|
-
|
|
389
388
|
/** Check if value is an array */
|
|
390
389
|
declare const isArr: <Item = unknown>(x: unknown) => x is Item[];
|
|
391
390
|
/**
|
|
@@ -660,6 +659,19 @@ type ThrottleOptions<ThisArg = unknown> = {
|
|
|
660
659
|
* @param config.tid (optional)
|
|
661
660
|
* @param config.thisArg (optional) the special `thisArgs` to be used when invoking the callback.
|
|
662
661
|
* @param config.trailing (optional) whether to enable trailing edge execution. Default: `true`
|
|
662
|
+
*
|
|
663
|
+
* @example
|
|
664
|
+
* ```javascript
|
|
665
|
+
* import { throttle } from '@superutils/core'
|
|
666
|
+
*
|
|
667
|
+
* const handleChange = throttle(
|
|
668
|
+
* event => console.log('Value:', event.target.value),
|
|
669
|
+
* 300, // throttle duration in milliseconds
|
|
670
|
+
* )
|
|
671
|
+
* handleChange({ target: { value: 1 } }) // will be executed
|
|
672
|
+
* handleChange({ target: { value: 2 } }) // will be ignored
|
|
673
|
+
* handleChange({ target: { value: 3 } }) // will be ignored
|
|
674
|
+
* ```
|
|
663
675
|
*/
|
|
664
676
|
declare const throttled: {
|
|
665
677
|
<TArgs extends unknown[], ThisArg>(callback: (this: ThisArg, ...args: TArgs) => ValueOrPromise<unknown>, delay?: number, config?: ThrottleOptions<ThisArg>): (...args: TArgs) => void;
|
|
@@ -1374,4 +1386,4 @@ declare const HASH_REGEX: RegExp;
|
|
|
1374
1386
|
*/
|
|
1375
1387
|
declare const strToArr: (value: unknown, seperator?: string) => string[];
|
|
1376
1388
|
|
|
1377
|
-
export { type ArrayComparator, type AsyncFn, type CreateTuple, type CurriedArgs, type Curry, type DeferredOptions, type DropFirst, type DropFirstN, type DropLast, EMAIL_REGEX, type EntryComparator, type FindOptions, HASH_REGEX, HEX_REGEX, type IfPromiseAddValue, type IsFiniteTuple, type IsOptional, type IterableList, type KeepFirst, type KeepFirstN, type KeepOptionals, type KeepRequired, type MakeOptional, type MinLength, type NegativeNumber, type OptionalIf, type PositiveNumber, type PositiveNumberWithZero, type ReadOnlyAllowAddFn, ReadOnlyArrayHelper, type ReadOnlyConfig, type SearchOptions, type Slice, type SliceMapOptions, type SliceMapTransform, type SortOptions, type ThrottleOptions, type TimeoutId, type TupleMaxLength, type TupleWithAlt, type ValueOrFunc, type ValueOrPromise, arrReadOnly, arrReverse, arrToMap, arrUnique,
|
|
1389
|
+
export { type ArrayComparator, type AsyncFn, type CreateTuple, type CurriedArgs, type Curry, type DeferredOptions, type DropFirst, type DropFirstN, type DropLast, EMAIL_REGEX, type EntryComparator, type FindOptions, HASH_REGEX, HEX_REGEX, type IfPromiseAddValue, type IsFiniteTuple, type IsOptional, type IterableList, type KeepFirst, type KeepFirstN, type KeepOptionals, type KeepRequired, type MakeOptional, type MinLength, type NegativeNumber, type OptionalIf, type PositiveNumber, type PositiveNumberWithZero, type ReadOnlyAllowAddFn, ReadOnlyArrayHelper, type ReadOnlyConfig, type SearchOptions, type Slice, type SliceMapOptions, type SliceMapTransform, type SortOptions, type ThrottleOptions, type TimeoutId, type TupleMaxLength, type TupleWithAlt, type ValueOrFunc, type ValueOrPromise, arrReadOnly, arrReverse, arrToMap, arrUnique, clearClutter, copyToClipboard, curry, debounce, deferred, fallbackIfFails, filter, find, getEntries, getKeys, getSize, getUrlParam, getValues, is, isArr, isArr2D, isArrLike, isArrLikeSafe, isArrObj, isArrUnique, isAsyncFn, isBool, isDate, isDateValid, isDefined, isEmpty, isEmptySafe, isEnvBrowser, isEnvNode, isEnvTouchable, isError, isFn, isInteger, isMap, isMapObj, isNumber, isObj, isPositiveInteger, isPositiveNumber, isPromise, isRegExp, isSet, isStr, isSymbol, isUint8Arr, isUrl, isUrlValid, mapJoin, matchObjOrProp, noop, noopAsync, objClean, objCopy, objCreate, objHasKeys, objKeys, objReadOnly, objSetProp, objSetPropUndefined, objSort, objWithoutKeys, randomInt, reverse, search, sliceMap, sort, strToArr, throttled, toDatetimeLocal };
|
package/dist/index.js
CHANGED
|
@@ -1,14 +1,9 @@
|
|
|
1
|
-
// src/forceCast.ts
|
|
2
|
-
var asAny = (x) => x;
|
|
3
|
-
var forceCast = (x) => x;
|
|
4
|
-
var forceCast_default = forceCast;
|
|
5
|
-
|
|
6
1
|
// src/curry.ts
|
|
7
2
|
function curry(func, ...[arity = func.length]) {
|
|
8
3
|
const curriedFn = (...args) => {
|
|
9
4
|
const _args = args;
|
|
10
|
-
if (_args.length >= arity) return func(...
|
|
11
|
-
return (...nextArgs) =>
|
|
5
|
+
if (_args.length >= arity) return func(...args);
|
|
6
|
+
return (...nextArgs) => curriedFn(
|
|
12
7
|
..._args,
|
|
13
8
|
...nextArgs
|
|
14
9
|
);
|
|
@@ -244,9 +239,7 @@ deferred.defaults = {
|
|
|
244
239
|
var deferred_default = deferred;
|
|
245
240
|
|
|
246
241
|
// src/debounce.ts
|
|
247
|
-
|
|
248
|
-
return deferred_default(...args);
|
|
249
|
-
}
|
|
242
|
+
var debounce = deferred_default;
|
|
250
243
|
|
|
251
244
|
// src/throttled.ts
|
|
252
245
|
var throttled = (callback, delay = 50, config = {}) => {
|
|
@@ -346,7 +339,7 @@ var objCopy = (input, output, ignoreKeys, override = false, recursive = true) =>
|
|
|
346
339
|
const value = input[key];
|
|
347
340
|
const skip = _output.hasOwnProperty(key) && (override === "empty" ? !isEmpty(_output[key]) : isFn(override) ? !override(key, _output[key], value) : true);
|
|
348
341
|
if (skip) continue;
|
|
349
|
-
const isPrimitive = [void 0, null, Infinity, NaN].includes(
|
|
342
|
+
const isPrimitive = [void 0, null, Infinity, NaN].includes(value) || !isObj(value, false);
|
|
350
343
|
if (isPrimitive) {
|
|
351
344
|
_output[key] = value;
|
|
352
345
|
continue;
|
|
@@ -356,26 +349,28 @@ var objCopy = (input, output, ignoreKeys, override = false, recursive = true) =>
|
|
|
356
349
|
case Array.prototype:
|
|
357
350
|
return clone(value, "[]");
|
|
358
351
|
case ArrayBuffer.prototype:
|
|
359
|
-
return
|
|
352
|
+
return value.slice(0);
|
|
360
353
|
case Date.prototype:
|
|
361
|
-
return new Date(
|
|
354
|
+
return new Date(value.getTime());
|
|
362
355
|
case Map.prototype:
|
|
363
356
|
return new Map(
|
|
364
357
|
clone(
|
|
365
|
-
Array.from(
|
|
358
|
+
Array.from(
|
|
359
|
+
value
|
|
360
|
+
),
|
|
366
361
|
"[]"
|
|
367
362
|
)
|
|
368
363
|
);
|
|
369
364
|
case RegExp.prototype:
|
|
370
|
-
return new RegExp(
|
|
365
|
+
return new RegExp(value);
|
|
371
366
|
case Set.prototype:
|
|
372
367
|
return new Set(
|
|
373
|
-
clone(Array.from(
|
|
368
|
+
clone(Array.from(value))
|
|
374
369
|
);
|
|
375
370
|
case Uint8Array.prototype:
|
|
376
|
-
return new Uint8Array([...
|
|
371
|
+
return new Uint8Array([...value]);
|
|
377
372
|
case URL.prototype:
|
|
378
|
-
return new URL(
|
|
373
|
+
return new URL(value);
|
|
379
374
|
default:
|
|
380
375
|
break;
|
|
381
376
|
}
|
|
@@ -917,7 +912,6 @@ export {
|
|
|
917
912
|
arrReverse,
|
|
918
913
|
arrToMap,
|
|
919
914
|
arrUnique,
|
|
920
|
-
asAny,
|
|
921
915
|
clearClutter,
|
|
922
916
|
copyToClipboard,
|
|
923
917
|
curry,
|
|
@@ -926,7 +920,6 @@ export {
|
|
|
926
920
|
fallbackIfFails,
|
|
927
921
|
filter,
|
|
928
922
|
find,
|
|
929
|
-
forceCast,
|
|
930
923
|
getEntries,
|
|
931
924
|
getKeys,
|
|
932
925
|
getSize,
|
package/package.json
CHANGED