@omnific/utils 0.0.4 → 0.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.
@@ -0,0 +1,78 @@
1
+ //#region debounce.d.ts
2
+ interface DebounceOptions {
3
+ /**
4
+ * An optional AbortSignal to cancel the debounced function.
5
+ */
6
+ signal?: AbortSignal;
7
+ /**
8
+ * An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both.
9
+ * If `edges` includes "leading", the function will be invoked at the start of the delay period.
10
+ * If `edges` includes "trailing", the function will be invoked at the end of the delay period.
11
+ * If both "leading" and "trailing" are included, the function will be invoked at both the start and end of the delay period.
12
+ * @default ["trailing"]
13
+ */
14
+ edges?: Array<'leading' | 'trailing'>;
15
+ }
16
+ interface DebouncedFunction<F extends (...args: any[]) => void> {
17
+ (...args: Parameters<F>): void;
18
+ /**
19
+ * Schedules the execution of the debounced function after the specified debounce delay.
20
+ * This method resets any existing timer, ensuring that the function is only invoked
21
+ * after the delay has elapsed since the last call to the debounced function.
22
+ * It is typically called internally whenever the debounced function is invoked.
23
+ *
24
+ * @returns {void}
25
+ */
26
+ schedule: () => void;
27
+ /**
28
+ * Cancels any pending execution of the debounced function.
29
+ * This method clears the active timer and resets any stored context or arguments.
30
+ */
31
+ cancel: () => void;
32
+ /**
33
+ * Immediately invokes the debounced function if there is a pending execution.
34
+ * This method executes the function right away if there is a pending execution.
35
+ */
36
+ flush: () => void;
37
+ }
38
+ /**
39
+ * Creates a debounced function that delays invoking the provided function until after `debounceMs` milliseconds
40
+ * have elapsed since the last time the debounced function was invoked. The debounced function also has a `cancel`
41
+ * method to cancel any pending execution.
42
+ *
43
+ * @template F - The type of function.
44
+ * @param {F} func - The function to debounce.
45
+ * @param {number} debounceMs - The number of milliseconds to delay.
46
+ * @param {DebounceOptions} options - The options object
47
+ * @param {AbortSignal} options.signal - An optional AbortSignal to cancel the debounced function.
48
+ * @returns A new debounced function with a `cancel` method.
49
+ *
50
+ * @example
51
+ * const debouncedFunction = debounce(() => {
52
+ * console.log('Function executed');
53
+ * }, 1000);
54
+ *
55
+ * // Will log 'Function executed' after 1 second if not called again in that time
56
+ * debouncedFunction();
57
+ *
58
+ * // Will not log anything as the previous call is canceled
59
+ * debouncedFunction.cancel();
60
+ *
61
+ * // With AbortSignal
62
+ * const controller = new AbortController();
63
+ * const signal = controller.signal;
64
+ * const debouncedWithSignal = debounce(() => {
65
+ * console.log('Function executed');
66
+ * }, 1000, { signal });
67
+ *
68
+ * debouncedWithSignal();
69
+ *
70
+ * // Will cancel the debounced function call
71
+ * controller.abort();
72
+ */
73
+ declare function debounce<F extends (...args: any[]) => void>(func: F, debounceMs: number, {
74
+ signal,
75
+ edges
76
+ }?: DebounceOptions): DebouncedFunction<F>;
77
+ //#endregion
78
+ export { DebounceOptions, DebouncedFunction, debounce };
@@ -0,0 +1,91 @@
1
+ import { isUndefined } from "./isUndefined.js";
2
+ import hasValue from "./hasValue.js";
3
+ //#region debounce.ts
4
+ /**
5
+ * Creates a debounced function that delays invoking the provided function until after `debounceMs` milliseconds
6
+ * have elapsed since the last time the debounced function was invoked. The debounced function also has a `cancel`
7
+ * method to cancel any pending execution.
8
+ *
9
+ * @template F - The type of function.
10
+ * @param {F} func - The function to debounce.
11
+ * @param {number} debounceMs - The number of milliseconds to delay.
12
+ * @param {DebounceOptions} options - The options object
13
+ * @param {AbortSignal} options.signal - An optional AbortSignal to cancel the debounced function.
14
+ * @returns A new debounced function with a `cancel` method.
15
+ *
16
+ * @example
17
+ * const debouncedFunction = debounce(() => {
18
+ * console.log('Function executed');
19
+ * }, 1000);
20
+ *
21
+ * // Will log 'Function executed' after 1 second if not called again in that time
22
+ * debouncedFunction();
23
+ *
24
+ * // Will not log anything as the previous call is canceled
25
+ * debouncedFunction.cancel();
26
+ *
27
+ * // With AbortSignal
28
+ * const controller = new AbortController();
29
+ * const signal = controller.signal;
30
+ * const debouncedWithSignal = debounce(() => {
31
+ * console.log('Function executed');
32
+ * }, 1000, { signal });
33
+ *
34
+ * debouncedWithSignal();
35
+ *
36
+ * // Will cancel the debounced function call
37
+ * controller.abort();
38
+ */
39
+ function debounce(func, debounceMs, { signal, edges } = {}) {
40
+ let pendingInvoke;
41
+ const leading = hasValue(edges) && edges.includes("leading");
42
+ const trailing = isUndefined(edges) || edges.includes("trailing");
43
+ const invoke = () => {
44
+ if (hasValue(pendingInvoke)) {
45
+ pendingInvoke();
46
+ pendingInvoke = void 0;
47
+ }
48
+ };
49
+ const onTimerEnd = () => {
50
+ if (trailing) invoke();
51
+ cancel();
52
+ };
53
+ let timeoutId;
54
+ const schedule = () => {
55
+ if (hasValue(timeoutId)) clearTimeout(timeoutId);
56
+ timeoutId = setTimeout(() => {
57
+ timeoutId = void 0;
58
+ onTimerEnd();
59
+ }, debounceMs);
60
+ };
61
+ const cancelTimer = () => {
62
+ if (hasValue(timeoutId)) {
63
+ clearTimeout(timeoutId);
64
+ timeoutId = void 0;
65
+ }
66
+ };
67
+ const cancel = () => {
68
+ cancelTimer();
69
+ pendingInvoke = void 0;
70
+ };
71
+ const flush = () => {
72
+ cancelTimer();
73
+ invoke();
74
+ };
75
+ const debounced = function(...args) {
76
+ if (signal?.aborted) return;
77
+ pendingInvoke = () => {
78
+ func.apply(this, args);
79
+ };
80
+ const isFirstCall = isUndefined(timeoutId);
81
+ schedule();
82
+ if (leading && isFirstCall) invoke();
83
+ };
84
+ debounced.schedule = schedule;
85
+ debounced.cancel = cancel;
86
+ debounced.flush = flush;
87
+ signal?.addEventListener("abort", cancel, { once: true });
88
+ return debounced;
89
+ }
90
+ //#endregion
91
+ export { debounce };
@@ -0,0 +1,21 @@
1
+ //#region isArrayBuffer.d.ts
2
+ /**
3
+ * Checks if a given value is `ArrayBuffer`.
4
+ *
5
+ * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `ArrayBuffer`.
6
+ *
7
+ * @param {unknown} value The value to check if it is `ArrayBuffer`.
8
+ * @returns {value is ArrayBuffer} Returns `true` if `value` is `ArrayBuffer`, else `false`.
9
+ *
10
+ * @example
11
+ * const value1 = new ArrayBuffer(8);
12
+ * const value2 = new Blob(['hello']);
13
+ * const value3 = {};
14
+ *
15
+ * console.log(isArrayBuffer(value1)); // true
16
+ * console.log(isArrayBuffer(value2)); // false
17
+ * console.log(isArrayBuffer(value3)); // false
18
+ */
19
+ declare function isArrayBuffer(value: unknown): value is ArrayBuffer;
20
+ //#endregion
21
+ export { isArrayBuffer };
@@ -0,0 +1,24 @@
1
+ import hasValue from "./hasValue.js";
2
+ //#region isArrayBuffer.ts
3
+ /**
4
+ * Checks if a given value is `ArrayBuffer`.
5
+ *
6
+ * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `ArrayBuffer`.
7
+ *
8
+ * @param {unknown} value The value to check if it is `ArrayBuffer`.
9
+ * @returns {value is ArrayBuffer} Returns `true` if `value` is `ArrayBuffer`, else `false`.
10
+ *
11
+ * @example
12
+ * const value1 = new ArrayBuffer(8);
13
+ * const value2 = new Blob(['hello']);
14
+ * const value3 = {};
15
+ *
16
+ * console.log(isArrayBuffer(value1)); // true
17
+ * console.log(isArrayBuffer(value2)); // false
18
+ * console.log(isArrayBuffer(value3)); // false
19
+ */
20
+ function isArrayBuffer(value) {
21
+ return hasValue(value) && value instanceof ArrayBuffer;
22
+ }
23
+ //#endregion
24
+ export { isArrayBuffer };
@@ -0,0 +1,21 @@
1
+ //#region isBlob.d.ts
2
+ /**
3
+ * Checks if a given value is `Blob`.
4
+ *
5
+ * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Blob`.
6
+ *
7
+ * @param {unknown} value The value to check if it is `Blob`.
8
+ * @returns {value is Blob} Returns `true` if `value` is `Blob`, else `false`.
9
+ *
10
+ * @example
11
+ * const value1 = new Blob(['hello']);
12
+ * const value2 = new ArrayBuffer(8);
13
+ * const value3 = {};
14
+ *
15
+ * console.log(isBlob(value1)); // true
16
+ * console.log(isBlob(value2)); // false
17
+ * console.log(isBlob(value3)); // false
18
+ */
19
+ declare function isBlob(value: unknown): value is Blob;
20
+ //#endregion
21
+ export { isBlob };
package/dist/isBlob.js ADDED
@@ -0,0 +1,24 @@
1
+ import hasValue from "./hasValue.js";
2
+ //#region isBlob.ts
3
+ /**
4
+ * Checks if a given value is `Blob`.
5
+ *
6
+ * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Blob`.
7
+ *
8
+ * @param {unknown} value The value to check if it is `Blob`.
9
+ * @returns {value is Blob} Returns `true` if `value` is `Blob`, else `false`.
10
+ *
11
+ * @example
12
+ * const value1 = new Blob(['hello']);
13
+ * const value2 = new ArrayBuffer(8);
14
+ * const value3 = {};
15
+ *
16
+ * console.log(isBlob(value1)); // true
17
+ * console.log(isBlob(value2)); // false
18
+ * console.log(isBlob(value3)); // false
19
+ */
20
+ function isBlob(value) {
21
+ return hasValue(value) && value instanceof Blob;
22
+ }
23
+ //#endregion
24
+ export { isBlob };
@@ -0,0 +1,21 @@
1
+ //#region isFormData.d.ts
2
+ /**
3
+ * Checks if a given value is `FormData`.
4
+ *
5
+ * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `FormData`.
6
+ *
7
+ * @param {unknown} value The value to check if it is `FormData`.
8
+ * @returns {value is FormData} Returns `true` if `value` is `FormData`, else `false`.
9
+ *
10
+ * @example
11
+ * const value1 = new FormData();
12
+ * const value2 = new URLSearchParams();
13
+ * const value3 = {};
14
+ *
15
+ * console.log(isFormData(value1)); // true
16
+ * console.log(isFormData(value2)); // false
17
+ * console.log(isFormData(value3)); // false
18
+ */
19
+ declare function isFormData(value: unknown): value is FormData;
20
+ //#endregion
21
+ export { isFormData };
@@ -0,0 +1,24 @@
1
+ import hasValue from "./hasValue.js";
2
+ //#region isFormData.ts
3
+ /**
4
+ * Checks if a given value is `FormData`.
5
+ *
6
+ * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `FormData`.
7
+ *
8
+ * @param {unknown} value The value to check if it is `FormData`.
9
+ * @returns {value is FormData} Returns `true` if `value` is `FormData`, else `false`.
10
+ *
11
+ * @example
12
+ * const value1 = new FormData();
13
+ * const value2 = new URLSearchParams();
14
+ * const value3 = {};
15
+ *
16
+ * console.log(isFormData(value1)); // true
17
+ * console.log(isFormData(value2)); // false
18
+ * console.log(isFormData(value3)); // false
19
+ */
20
+ function isFormData(value) {
21
+ return hasValue(value) && value instanceof FormData;
22
+ }
23
+ //#endregion
24
+ export { isFormData };
@@ -0,0 +1,46 @@
1
+ //#region isPlainObject.d.ts
2
+ /**
3
+ * Checks if a given value is a plain object.
4
+ *
5
+ * @param {object} value - The value to check.
6
+ * @returns {value is Record<PropertyKey, any>} - True if the value is a plain object, otherwise false.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * // ✅ True
11
+ *
12
+ * isPlainObject({}); // ✅
13
+ * isPlainObject({ key: 'value' }); // ✅
14
+ * isPlainObject({ key: new Date() }); // ✅
15
+ * isPlainObject(new Object()); // ✅
16
+ * isPlainObject(Object.create(null)); // ✅
17
+ * isPlainObject({ nested: { key: true } }); // ✅
18
+ * isPlainObject(new Proxy({}, {})); // ✅
19
+ * isPlainObject({ [Symbol('tag')]: 'A' }); // ✅
20
+ *
21
+ * // ✅ (cross-realms, node context, workers, ...)
22
+ * const runInNewContext = await import('node:vm').then(
23
+ * mod => mod.runInNewContext
24
+ * );
25
+ * isPlainObject(runInNewContext('({})')); // ✅
26
+ *
27
+ * // ❌ False
28
+ *
29
+ * class Test {}
30
+ * isPlainObject(new Test()); // ❌
31
+ * isPlainObject(10); // ❌
32
+ * isPlainObject(null); // ❌
33
+ * isPlainObject('hello'); // ❌
34
+ * isPlainObject([]); // ❌
35
+ * isPlainObject(new Date()); // ❌
36
+ * isPlainObject(new Uint8Array([1])); // ❌
37
+ * isPlainObject(Buffer.from('ABC')); // ❌
38
+ * isPlainObject(Promise.resolve({})); // ❌
39
+ * isPlainObject(Object.create({})); // ❌
40
+ * isPlainObject(new (class Cls {})()); // ❌
41
+ * isPlainObject(globalThis); // ❌
42
+ * ```
43
+ */
44
+ declare function isPlainObject(value: unknown): value is Record<PropertyKey, any>;
45
+ //#endregion
46
+ export { isPlainObject };
@@ -0,0 +1,53 @@
1
+ import { isNull } from "./isNull.js";
2
+ import { isObject } from "./isObject.js";
3
+ //#region isPlainObject.ts
4
+ /**
5
+ * Checks if a given value is a plain object.
6
+ *
7
+ * @param {object} value - The value to check.
8
+ * @returns {value is Record<PropertyKey, any>} - True if the value is a plain object, otherwise false.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * // ✅ True
13
+ *
14
+ * isPlainObject({}); // ✅
15
+ * isPlainObject({ key: 'value' }); // ✅
16
+ * isPlainObject({ key: new Date() }); // ✅
17
+ * isPlainObject(new Object()); // ✅
18
+ * isPlainObject(Object.create(null)); // ✅
19
+ * isPlainObject({ nested: { key: true } }); // ✅
20
+ * isPlainObject(new Proxy({}, {})); // ✅
21
+ * isPlainObject({ [Symbol('tag')]: 'A' }); // ✅
22
+ *
23
+ * // ✅ (cross-realms, node context, workers, ...)
24
+ * const runInNewContext = await import('node:vm').then(
25
+ * mod => mod.runInNewContext
26
+ * );
27
+ * isPlainObject(runInNewContext('({})')); // ✅
28
+ *
29
+ * // ❌ False
30
+ *
31
+ * class Test {}
32
+ * isPlainObject(new Test()); // ❌
33
+ * isPlainObject(10); // ❌
34
+ * isPlainObject(null); // ❌
35
+ * isPlainObject('hello'); // ❌
36
+ * isPlainObject([]); // ❌
37
+ * isPlainObject(new Date()); // ❌
38
+ * isPlainObject(new Uint8Array([1])); // ❌
39
+ * isPlainObject(Buffer.from('ABC')); // ❌
40
+ * isPlainObject(Promise.resolve({})); // ❌
41
+ * isPlainObject(Object.create({})); // ❌
42
+ * isPlainObject(new (class Cls {})()); // ❌
43
+ * isPlainObject(globalThis); // ❌
44
+ * ```
45
+ */
46
+ function isPlainObject(value) {
47
+ if (!isObject(value)) return false;
48
+ const proto = Object.getPrototypeOf(value);
49
+ if (!(isNull(proto) || proto === Object.prototype || isNull(Object.getPrototypeOf(proto)))) return false;
50
+ return Object.prototype.toString.call(value) === "[object Object]";
51
+ }
52
+ //#endregion
53
+ export { isPlainObject };
@@ -0,0 +1,21 @@
1
+ //#region isURLSearchParams.d.ts
2
+ /**
3
+ * Checks if a given value is `URLSearchParams`.
4
+ *
5
+ * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `URLSearchParams`.
6
+ *
7
+ * @param {unknown} value The value to check if it is `URLSearchParams`.
8
+ * @returns {value is URLSearchParams} Returns `true` if `value` is `URLSearchParams`, else `false`.
9
+ *
10
+ * @example
11
+ * const value1 = new URLSearchParams('a=1');
12
+ * const value2 = new FormData();
13
+ * const value3 = 'a=1';
14
+ *
15
+ * console.log(isURLSearchParams(value1)); // true
16
+ * console.log(isURLSearchParams(value2)); // false
17
+ * console.log(isURLSearchParams(value3)); // false
18
+ */
19
+ declare function isURLSearchParams(value: unknown): value is URLSearchParams;
20
+ //#endregion
21
+ export { isURLSearchParams };
@@ -0,0 +1,24 @@
1
+ import hasValue from "./hasValue.js";
2
+ //#region isURLSearchParams.ts
3
+ /**
4
+ * Checks if a given value is `URLSearchParams`.
5
+ *
6
+ * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `URLSearchParams`.
7
+ *
8
+ * @param {unknown} value The value to check if it is `URLSearchParams`.
9
+ * @returns {value is URLSearchParams} Returns `true` if `value` is `URLSearchParams`, else `false`.
10
+ *
11
+ * @example
12
+ * const value1 = new URLSearchParams('a=1');
13
+ * const value2 = new FormData();
14
+ * const value3 = 'a=1';
15
+ *
16
+ * console.log(isURLSearchParams(value1)); // true
17
+ * console.log(isURLSearchParams(value2)); // false
18
+ * console.log(isURLSearchParams(value3)); // false
19
+ */
20
+ function isURLSearchParams(value) {
21
+ return hasValue(value) && value instanceof URLSearchParams;
22
+ }
23
+ //#endregion
24
+ export { isURLSearchParams };
package/dist/main.d.ts CHANGED
@@ -1,16 +1,25 @@
1
1
  import { ChainedFunction, createChainedFunction } from "./createChainedFunction.js";
2
+ import { DebounceOptions, DebouncedFunction, debounce } from "./debounce.js";
2
3
  import { get } from "./get.js";
3
4
  import hasValue from "./hasValue.js";
4
5
  import { isArray } from "./isArray.js";
6
+ import { isArrayBuffer } from "./isArrayBuffer.js";
7
+ import { isBlob } from "./isBlob.js";
5
8
  import { isBoolean } from "./isBoolean.js";
9
+ import { isFormData } from "./isFormData.js";
6
10
  import { isFunction } from "./isFunction.js";
7
11
  import { isNil } from "./isNil.js";
8
12
  import { isNull } from "./isNull.js";
9
13
  import { isNumber } from "./isNumber.js";
10
14
  import { isObject } from "./isObject.js";
15
+ import { isPlainObject } from "./isPlainObject.js";
11
16
  import { isPromise } from "./isPromise.js";
12
17
  import { isString } from "./isString.js";
13
18
  import { isSymbol } from "./isSymbol.js";
19
+ import { isURLSearchParams } from "./isURLSearchParams.js";
14
20
  import { isUndefined } from "./isUndefined.js";
21
+ import { parseJson } from "./parseJson.js";
22
+ import { ThrottleOptions, ThrottledFunction, throttle } from "./throttle.js";
15
23
  import resolveValue from "./resolveValue.js";
16
- export { type ChainedFunction, createChainedFunction, get, hasValue, isArray, isBoolean, isFunction, isNil, isNull, isNumber, isObject, isPromise, isString, isSymbol, isUndefined, resolveValue };
24
+ import { uniqueId } from "./uniqueId.js";
25
+ export { type ChainedFunction, type DebounceOptions, type DebouncedFunction, type ThrottleOptions, type ThrottledFunction, createChainedFunction, debounce, get, hasValue, isArray, isArrayBuffer, isBlob, isBoolean, isFormData, isFunction, isNil, isNull, isNumber, isObject, isPlainObject, isPromise, isString, isSymbol, isURLSearchParams, isUndefined, parseJson, resolveValue, throttle, uniqueId };
package/dist/main.js CHANGED
@@ -1,16 +1,25 @@
1
1
  import { isArray } from "./isArray.js";
2
2
  import { isBoolean } from "./isBoolean.js";
3
- import { isFunction } from "./isFunction.js";
4
- import { createChainedFunction } from "./createChainedFunction.js";
5
3
  import { isUndefined } from "./isUndefined.js";
6
4
  import { isNull } from "./isNull.js";
7
5
  import { isNil } from "./isNil.js";
8
6
  import hasValue from "./hasValue.js";
7
+ import { isBlob } from "./isBlob.js";
8
+ import { isFunction } from "./isFunction.js";
9
+ import { createChainedFunction } from "./createChainedFunction.js";
10
+ import { debounce } from "./debounce.js";
11
+ import { isFormData } from "./isFormData.js";
9
12
  import { isNumber } from "./isNumber.js";
10
- import { isString } from "./isString.js";
11
13
  import { isObject } from "./isObject.js";
14
+ import { isPlainObject } from "./isPlainObject.js";
15
+ import { isString } from "./isString.js";
12
16
  import { isPromise } from "./isPromise.js";
17
+ import { isArrayBuffer } from "./isArrayBuffer.js";
18
+ import { isURLSearchParams } from "./isURLSearchParams.js";
19
+ import { parseJson } from "./parseJson.js";
13
20
  import { isSymbol } from "./isSymbol.js";
14
21
  import { get } from "./get.js";
22
+ import { throttle } from "./throttle.js";
15
23
  import resolveValue from "./resolveValue.js";
16
- export { createChainedFunction, get, hasValue, isArray, isBoolean, isFunction, isNil, isNull, isNumber, isObject, isPromise, isString, isSymbol, isUndefined, resolveValue };
24
+ import { uniqueId } from "./uniqueId.js";
25
+ export { createChainedFunction, debounce, get, hasValue, isArray, isArrayBuffer, isBlob, isBoolean, isFormData, isFunction, isNil, isNull, isNumber, isObject, isPlainObject, isPromise, isString, isSymbol, isURLSearchParams, isUndefined, parseJson, resolveValue, throttle, uniqueId };
@@ -0,0 +1,10 @@
1
+ //#region parseJson.d.ts
2
+ /**
3
+ * Parses JSON text into a value.
4
+ *
5
+ * Returns `undefined` for blank strings. When `fallback` is provided, invalid JSON
6
+ * returns the fallback instead of throwing.
7
+ */
8
+ declare function parseJson<T>(text: string, fallback?: T): T | undefined;
9
+ //#endregion
10
+ export { parseJson };
@@ -0,0 +1,18 @@
1
+ //#region parseJson.ts
2
+ /**
3
+ * Parses JSON text into a value.
4
+ *
5
+ * Returns `undefined` for blank strings. When `fallback` is provided, invalid JSON
6
+ * returns the fallback instead of throwing.
7
+ */
8
+ function parseJson(text, fallback) {
9
+ if (!text.trim()) return;
10
+ try {
11
+ return JSON.parse(text);
12
+ } catch (error) {
13
+ if (arguments.length > 1) return fallback;
14
+ throw error;
15
+ }
16
+ }
17
+ //#endregion
18
+ export { parseJson };
@@ -0,0 +1,52 @@
1
+ //#region throttle.d.ts
2
+ interface ThrottleOptions {
3
+ /**
4
+ * An optional AbortSignal to cancel the throttled function.
5
+ */
6
+ signal?: AbortSignal;
7
+ /**
8
+ * An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both.
9
+ * If `edges` includes "leading", the function will be invoked at the start of the delay period.
10
+ * If `edges` includes "trailing", the function will be invoked at the end of the delay period.
11
+ * If both "leading" and "trailing" are included, the function will be invoked at both the start and end of the delay period.
12
+ * @default ["leading", "trailing"]
13
+ */
14
+ edges?: Array<'leading' | 'trailing'>;
15
+ }
16
+ interface ThrottledFunction<F extends (...args: any[]) => void> {
17
+ (...args: Parameters<F>): void;
18
+ cancel: () => void;
19
+ flush: () => void;
20
+ }
21
+ /**
22
+ * Creates a throttled function that only invokes the provided function at most once
23
+ * per every `throttleMs` milliseconds. Subsequent calls to the throttled function
24
+ * within the wait time will not trigger the execution of the original function.
25
+ *
26
+ * @template F - The type of function.
27
+ * @param {F} func - The function to throttle.
28
+ * @param {number} throttleMs - The number of milliseconds to throttle executions to.
29
+ * @returns {(...args: Parameters<F>) => void} A new throttled function that accepts the same parameters as the original function.
30
+ *
31
+ * @example
32
+ * const throttledFunction = throttle(() => {
33
+ * console.log('Function executed');
34
+ * }, 1000);
35
+ *
36
+ * // Will log 'Function executed' immediately
37
+ * throttledFunction();
38
+ *
39
+ * // Will not log anything as it is within the throttle time
40
+ * throttledFunction();
41
+ *
42
+ * // After 1 second
43
+ * setTimeout(() => {
44
+ * throttledFunction(); // Will log 'Function executed'
45
+ * }, 1000);
46
+ */
47
+ declare function throttle<F extends (...args: any[]) => void>(func: F, throttleMs: number, {
48
+ signal,
49
+ edges
50
+ }?: ThrottleOptions): ThrottledFunction<F>;
51
+ //#endregion
52
+ export { ThrottleOptions, ThrottledFunction, throttle };
@@ -0,0 +1,58 @@
1
+ import { isUndefined } from "./isUndefined.js";
2
+ import { debounce } from "./debounce.js";
3
+ //#region throttle.ts
4
+ /**
5
+ * Creates a throttled function that only invokes the provided function at most once
6
+ * per every `throttleMs` milliseconds. Subsequent calls to the throttled function
7
+ * within the wait time will not trigger the execution of the original function.
8
+ *
9
+ * @template F - The type of function.
10
+ * @param {F} func - The function to throttle.
11
+ * @param {number} throttleMs - The number of milliseconds to throttle executions to.
12
+ * @returns {(...args: Parameters<F>) => void} A new throttled function that accepts the same parameters as the original function.
13
+ *
14
+ * @example
15
+ * const throttledFunction = throttle(() => {
16
+ * console.log('Function executed');
17
+ * }, 1000);
18
+ *
19
+ * // Will log 'Function executed' immediately
20
+ * throttledFunction();
21
+ *
22
+ * // Will not log anything as it is within the throttle time
23
+ * throttledFunction();
24
+ *
25
+ * // After 1 second
26
+ * setTimeout(() => {
27
+ * throttledFunction(); // Will log 'Function executed'
28
+ * }, 1000);
29
+ */
30
+ function throttle(func, throttleMs, { signal, edges = ["leading", "trailing"] } = {}) {
31
+ let pendingAt;
32
+ const debounced = debounce(function(...args) {
33
+ pendingAt = Date.now();
34
+ func.apply(this, args);
35
+ }, throttleMs, {
36
+ signal,
37
+ edges
38
+ });
39
+ const throttled = function(...args) {
40
+ if (isUndefined(pendingAt)) pendingAt = Date.now();
41
+ if (Date.now() - pendingAt >= throttleMs) {
42
+ pendingAt = Date.now();
43
+ func.apply(this, args);
44
+ debounced.cancel();
45
+ debounced.schedule();
46
+ return;
47
+ }
48
+ debounced.apply(this, args);
49
+ };
50
+ throttled.cancel = () => {
51
+ pendingAt = void 0;
52
+ debounced.cancel();
53
+ };
54
+ throttled.flush = debounced.flush;
55
+ return throttled;
56
+ }
57
+ //#endregion
58
+ export { throttle };
@@ -0,0 +1,17 @@
1
+ //#region uniqueId.d.ts
2
+ /**
3
+ * Generates a unique ID.
4
+ *
5
+ * If `prefix` is provided, the generated ID is appended to it.
6
+ *
7
+ * @param {string} prefix - The value to prefix the generated ID with.
8
+ * @returns {string} Returns the unique ID.
9
+ *
10
+ * @example
11
+ * uniqueId(); // '1'
12
+ * uniqueId('contact_'); // 'contact_2'
13
+ * uniqueId('contact_'); // 'contact_3'
14
+ */
15
+ declare function uniqueId(prefix?: string): string;
16
+ //#endregion
17
+ export { uniqueId };
@@ -0,0 +1,20 @@
1
+ //#region uniqueId.ts
2
+ let idCounter = 0;
3
+ /**
4
+ * Generates a unique ID.
5
+ *
6
+ * If `prefix` is provided, the generated ID is appended to it.
7
+ *
8
+ * @param {string} prefix - The value to prefix the generated ID with.
9
+ * @returns {string} Returns the unique ID.
10
+ *
11
+ * @example
12
+ * uniqueId(); // '1'
13
+ * uniqueId('contact_'); // 'contact_2'
14
+ * uniqueId('contact_'); // 'contact_3'
15
+ */
16
+ function uniqueId(prefix = "") {
17
+ return `${prefix}${++idCounter}`;
18
+ }
19
+ //#endregion
20
+ export { uniqueId };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omnific/utils",
3
- "version": "0.0.4",
3
+ "version": "0.1.0",
4
4
  "description": "Shared utility predicates for Omnific packages",
5
5
  "license": "MIT",
6
6
  "type": "module",