@ibodr/utils 0.2.6 → 0.2.7

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/dist/index.d.ts CHANGED
@@ -706,6 +706,12 @@ type MakeUndefinedOptional<T extends object> = Expand<{
706
706
  * function returns a Promise that resolves with the result of the original function. Includes a
707
707
  * cancel method to prevent execution if needed.
708
708
  *
709
+ * Calling `cancel()` while a call is pending rejects the returned promise with an `Error`
710
+ * whose message is `'Debounced function was cancelled'`. Callers that discard the promise
711
+ * are not affected — internal handling suppresses the unhandled-rejection warning — but
712
+ * any code that `await`s or chains `.then()` on the promise must be prepared to handle the
713
+ * rejection.
714
+ *
709
715
  * @param callback - The function to debounce (can be sync or async)
710
716
  * @param wait - The delay in milliseconds before executing the function
711
717
  * @returns A debounced function that returns a Promise and includes a cancel method
@@ -721,15 +727,19 @@ type MakeUndefinedOptional<T extends object> = Expand<{
721
727
  * debouncedSearch('react hooks') // This cancels the previous call
722
728
  * debouncedSearch('react typescript') // Only this will execute
723
729
  *
724
- * // Cancel pending execution
730
+ * // Cancel pending execution — any in-flight promise rejects
725
731
  * debouncedSearch.cancel()
726
732
  *
727
- * // With async/await
733
+ * // With async/await — wrap in try/catch if you might cancel
728
734
  * const saveData = debounce(async (data: any) => {
729
735
  * return await api.save(data)
730
736
  * }, 1000)
731
737
  *
732
- * const result = await saveData({name: 'John'})
738
+ * try {
739
+ * const result = await saveData({name: 'John'})
740
+ * } catch (err) {
741
+ * // handle cancellation or callback error
742
+ * }
733
743
  * ```
734
744
  *
735
745
  * @public
@@ -1072,7 +1082,7 @@ declare function omitFromStackTrace<Args extends Array<unknown>, Return>(fn: (..
1072
1082
  * Does nothing, but it's really really good at it.
1073
1083
  * @internal
1074
1084
  */
1075
- declare const noop: () => void;
1085
+ declare function noop(): void;
1076
1086
 
1077
1087
  /**
1078
1088
  * Hash a string using the FNV-1a algorithm.
@@ -1256,17 +1266,6 @@ declare function uniqueId(size?: number): string;
1256
1266
  */
1257
1267
  declare function getFirstFromIterable<T = unknown>(set: Set<T> | Map<any, T>): T;
1258
1268
 
1259
- /** Simple LRU cache backed by a Map's insertion-order iteration. @public */
1260
- declare class LruCache<K, V> {
1261
- private maxSize;
1262
- private map;
1263
- constructor(maxSize: number);
1264
- get(key: K): V | undefined;
1265
- set(key: K, value: V): void;
1266
- has(key: K): boolean;
1267
- get size(): number;
1268
- }
1269
-
1270
1269
  /**
1271
1270
  * A type that represents any valid JSON value. This includes primitives (boolean, null, string, number),
1272
1271
  * arrays of JSON values, and objects with string keys and JSON values.
@@ -1342,6 +1341,18 @@ interface JsonObject {
1342
1341
  [key: string]: JsonValue | undefined;
1343
1342
  }
1344
1343
 
1344
+ /** Simple LRU cache backed by a Map's insertion-order iteration. @public */
1345
+ declare class LruCache<K, V> {
1346
+ private maxSize;
1347
+ private map;
1348
+ constructor(maxSize: number);
1349
+ get(key: K): V | undefined;
1350
+ set(key: K, value: V): void;
1351
+ has(key: K): boolean;
1352
+ delete(key: K): boolean;
1353
+ get size(): number;
1354
+ }
1355
+
1345
1356
  /**
1346
1357
  * Array of all supported image MIME types, combining static, vector, and animated types.
1347
1358
  *
@@ -1786,7 +1797,7 @@ declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Re
1786
1797
  * @returns HTMLImageElement with referrerPolicy set to 'strict-origin-when-cross-origin'
1787
1798
  * @internal
1788
1799
  */
1789
- declare const Image: (width?: number, height?: number) => HTMLImageElement;
1800
+ declare function Image(width?: number, height?: number): HTMLImageElement;
1790
1801
 
1791
1802
  /**
1792
1803
  * Linear interpolate between two values.
@@ -2596,6 +2607,32 @@ declare function deleteFromSessionStorage(key: string): void;
2596
2607
  */
2597
2608
  declare function clearSessionStorage(): void;
2598
2609
 
2610
+ /**
2611
+ * Iterate over the grapheme clusters of a string — user-perceived characters such as emoji
2612
+ * sequences, flags, and accented letters — instead of UTF-16 code units. Uses `Intl.Segmenter`
2613
+ * where available and falls back to iterating by code point on browsers that lack it, where a
2614
+ * multi-code-point cluster is yielded as its component code points rather than as one segment.
2615
+ *
2616
+ * @public
2617
+ */
2618
+ declare function iterateGraphemes(str: string): IterableIterator<string>;
2619
+ /**
2620
+ * Get the first character of a string, treating a multi-code-unit character such as an emoji as a
2621
+ * single character. Unlike `str[0]` or `str.charAt(0)`, which return one UTF-16 code unit and so
2622
+ * split an emoji into a broken half, this returns the first whole grapheme cluster. Returns an
2623
+ * empty string when the input is empty.
2624
+ *
2625
+ * @example
2626
+ * ```ts
2627
+ * getFirstCharacter('hello') // 'h'
2628
+ * getFirstCharacter('😀 hello') // '😀'
2629
+ * getFirstCharacter('') // ''
2630
+ * ```
2631
+ *
2632
+ * @public
2633
+ */
2634
+ declare function getFirstCharacter(str: string): string;
2635
+
2599
2636
  /**
2600
2637
  * Creates an enum-like object from string values where each key maps to itself.
2601
2638
  * Useful for creating string constant objects with type safety and autocompletion.
@@ -2817,6 +2854,47 @@ declare class Timers {
2817
2854
  * @public
2818
2855
  */
2819
2856
  requestAnimationFrame(contextId: string, callback: FrameRequestCallback): number;
2857
+ /**
2858
+ * Clears a timeout created with {@link Timers.setTimeout} and stops tracking it.
2859
+ * Prefer this over the global `clearTimeout` for ids that came from this instance,
2860
+ * otherwise the id stays tracked until its context is disposed.
2861
+ * @param contextId - The context identifier the timeout was created under.
2862
+ * @param id - The timer ID returned by `setTimeout`. Ignored when undefined.
2863
+ * @example
2864
+ * ```ts
2865
+ * const timers = new Timers()
2866
+ * const id = timers.setTimeout('autosave', () => save(), 5000)
2867
+ * timers.clearTimeout('autosave', id)
2868
+ * ```
2869
+ * @public
2870
+ */
2871
+ clearTimeout(contextId: string, id: number | undefined): void;
2872
+ /**
2873
+ * Clears an interval created with {@link Timers.setInterval} and stops tracking it.
2874
+ * @param contextId - The context identifier the interval was created under.
2875
+ * @param id - The interval ID returned by `setInterval`. Ignored when undefined.
2876
+ * @example
2877
+ * ```ts
2878
+ * const timers = new Timers()
2879
+ * const id = timers.setInterval('refresh', () => updateData(), 1000)
2880
+ * timers.clearInterval('refresh', id)
2881
+ * ```
2882
+ * @public
2883
+ */
2884
+ clearInterval(contextId: string, id: number | undefined): void;
2885
+ /**
2886
+ * Cancels an animation frame requested with {@link Timers.requestAnimationFrame} and stops tracking it.
2887
+ * @param contextId - The context identifier the animation frame was requested under.
2888
+ * @param id - The request ID returned by `requestAnimationFrame`. Ignored when undefined.
2889
+ * @example
2890
+ * ```ts
2891
+ * const timers = new Timers()
2892
+ * const id = timers.requestAnimationFrame('render', () => draw())
2893
+ * timers.cancelAnimationFrame('render', id)
2894
+ * ```
2895
+ * @public
2896
+ */
2897
+ cancelAnimationFrame(contextId: string, id: number | undefined): void;
2820
2898
  /**
2821
2899
  * Disposes of all timers associated with the specified context.
2822
2900
  * Clears all timeouts, intervals, and animation frames for the given context ID.
@@ -2854,17 +2932,20 @@ declare class Timers {
2854
2932
  * Returns an object with timer methods bound to a specific context.
2855
2933
  * Convenient for getting context-specific timer functions without repeatedly passing the contextId.
2856
2934
  * @param contextId - The context identifier to bind the returned methods to.
2857
- * @returns An object with setTimeout, setInterval, requestAnimationFrame, and dispose methods bound to the context.
2935
+ * @returns An object with setTimeout, setInterval, requestAnimationFrame, the matching clear methods, and dispose bound to the context.
2858
2936
  * @example
2859
2937
  * ```ts
2860
2938
  * const timers = new Timers()
2861
2939
  * const uiTimers = timers.forContext('ui')
2862
2940
  *
2863
2941
  * // These are equivalent to calling timers.setTimeout('ui', ...)
2864
- * uiTimers.setTimeout(() => console.log('timeout'), 1000)
2942
+ * const id = uiTimers.setTimeout(() => console.log('timeout'), 1000)
2865
2943
  * uiTimers.setInterval(() => console.log('interval'), 500)
2866
2944
  * uiTimers.requestAnimationFrame(() => console.log('frame'))
2867
2945
  *
2946
+ * // Clear a single timer
2947
+ * uiTimers.clearTimeout(id)
2948
+ *
2868
2949
  * // Dispose only this context
2869
2950
  * uiTimers.dispose()
2870
2951
  * ```
@@ -2874,6 +2955,9 @@ declare class Timers {
2874
2955
  setTimeout: (handler: TimerHandler, timeout?: number, ...args: any[]) => number;
2875
2956
  setInterval: (handler: TimerHandler, timeout?: number, ...args: any[]) => number;
2876
2957
  requestAnimationFrame: (callback: FrameRequestCallback) => number;
2958
+ clearTimeout: (id: number | undefined) => void;
2959
+ clearInterval: (id: number | undefined) => void;
2960
+ cancelAnimationFrame: (id: number | undefined) => void;
2877
2961
  dispose: () => void;
2878
2962
  };
2879
2963
  }
@@ -2918,7 +3002,7 @@ declare class Timers {
2918
3002
  *
2919
3003
  * @public
2920
3004
  */
2921
- declare const safeParseUrl: (url: string, baseUrl?: string | URL) => URL | undefined;
3005
+ declare function safeParseUrl(url: string, baseUrl?: string | URL): URL | undefined;
2922
3006
 
2923
3007
  /**
2924
3008
  * Get whether a value is not undefined.
@@ -3080,4 +3164,4 @@ declare function warnDeprecatedGetter(name: string): void;
3080
3164
  */
3081
3165
  declare function warnOnce(message: string): void;
3082
3166
 
3083
- export { type Awaitable, DEFAULT_SUPPORTED_IMAGE_TYPES, DEFAULT_SUPPORTED_MEDIA_TYPES, DEFAULT_SUPPORTED_MEDIA_TYPE_LIST, DEFAULT_SUPPORT_VIDEO_TYPES, type ErrorAnnotations, type ErrorResult, ExecutionQueue, type Expand, FileHelpers, FpsScheduler, Image, type IndexKey, type JsonArray, type JsonObject, type JsonPrimitive, type JsonValue, LruCache, type MakeUndefinedOptional, MediaHelpers, type OkResult, PerformanceTracker, PngHelpers, type RecursivePartial, type Required, Result, STRUCTURED_CLONE_OBJECT_PROTOTYPE, Timers, WeakCache, ZERO_INDEX_KEY, annotateError, areArraysShallowEqual, areObjectsShallowEqual, assert, assertExists, bind, clearLocalStorage, clearSessionStorage, compact, debounce, dedupe, deleteFromLocalStorage, deleteFromSessionStorage, exhaustiveSwitchError, fetch, filterEntries, fpsThrottle, getChangedKeys, getErrorAnnotations, getFirstFromIterable, getFromLocalStorage, getFromSessionStorage, getHashForBuffer, getHashForObject, getHashForString, getIndexAbove, getIndexBelow, getIndexBetween, getIndices, getIndicesAbove, getIndicesBelow, getIndicesBetween, getOwnProperty, groupBy, hasOwnProperty, invLerp, isDefined, isEqualAllowingForFloatingPointErrors, isNativeStructuredClone, isNonNull, isNonNullish, last, lerp, lns, mapObjectMapValues, maxBy, measureAverageDuration, measureCbDuration, measureDuration, mergeArraysAndReplaceDefaults, minBy, mockUniqueId, modulate, noop, objectMapEntries, objectMapEntriesIterable, objectMapFromEntries, objectMapKeys, objectMapValues, omit, omitFromStackTrace, partition, promiseWithResolve, registerDrawLibraryVersion, restoreUniqueId, retry, rng, rotateArray, safeParseUrl, setInLocalStorage, setInSessionStorage, sleep, sortById, sortByIndex, sortByMaybeIndex, stringEnum, structuredClone, throttleToNextFrame, uniqueId, validateIndexKey, warnDeprecatedGetter, warnOnce };
3167
+ export { type Awaitable, DEFAULT_SUPPORTED_IMAGE_TYPES, DEFAULT_SUPPORTED_MEDIA_TYPES, DEFAULT_SUPPORTED_MEDIA_TYPE_LIST, DEFAULT_SUPPORT_VIDEO_TYPES, type ErrorAnnotations, type ErrorResult, ExecutionQueue, type Expand, FileHelpers, FpsScheduler, Image, type IndexKey, type JsonArray, type JsonObject, type JsonPrimitive, type JsonValue, LruCache, type MakeUndefinedOptional, MediaHelpers, type OkResult, PerformanceTracker, PngHelpers, type RecursivePartial, type Required, Result, STRUCTURED_CLONE_OBJECT_PROTOTYPE, Timers, WeakCache, ZERO_INDEX_KEY, annotateError, areArraysShallowEqual, areObjectsShallowEqual, assert, assertExists, bind, clearLocalStorage, clearSessionStorage, compact, debounce, dedupe, deleteFromLocalStorage, deleteFromSessionStorage, exhaustiveSwitchError, fetch, filterEntries, fpsThrottle, getChangedKeys, getErrorAnnotations, getFirstCharacter, getFirstFromIterable, getFromLocalStorage, getFromSessionStorage, getHashForBuffer, getHashForObject, getHashForString, getIndexAbove, getIndexBelow, getIndexBetween, getIndices, getIndicesAbove, getIndicesBelow, getIndicesBetween, getOwnProperty, groupBy, hasOwnProperty, invLerp, isDefined, isEqualAllowingForFloatingPointErrors, isNativeStructuredClone, isNonNull, isNonNullish, iterateGraphemes, last, lerp, lns, mapObjectMapValues, maxBy, measureAverageDuration, measureCbDuration, measureDuration, mergeArraysAndReplaceDefaults, minBy, mockUniqueId, modulate, noop, objectMapEntries, objectMapEntriesIterable, objectMapFromEntries, objectMapKeys, objectMapValues, omit, omitFromStackTrace, partition, promiseWithResolve, registerDrawLibraryVersion, restoreUniqueId, retry, rng, rotateArray, safeParseUrl, setInLocalStorage, setInSessionStorage, sleep, sortById, sortByIndex, sortByMaybeIndex, stringEnum, structuredClone, throttleToNextFrame, uniqueId, validateIndexKey, warnDeprecatedGetter, warnOnce };