@tally.paws/toolbox 1.2.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,368 @@
1
+ interface DebouncedFunction<T extends (...args: any[]) => any> {
2
+ (...args: Parameters<T>): void;
3
+ cancel: () => void;
4
+ flush: () => void;
5
+ }
6
+ /**
7
+ * Debounces a function to prevent excessive calling.
8
+ * @param fn The function to debounce.
9
+ * @param delay The number of milliseconds to wait after the last call before calling the function again.
10
+ * @param options Immediate: If True, it will call the function immediately if more than the delay milliseconds since last call has passed. Any further calls within delay milliseconds will be debounced.
11
+ * @returns The Debounced function.
12
+ */
13
+ declare function debounce<T extends (...args: any[]) => any>(fn: T, delay?: number, options?: {
14
+ immediate?: boolean;
15
+ }): DebouncedFunction<T>;
16
+ /**
17
+ * Throttles a function to only run once for every interval of time.
18
+ * @param fn The function to throttle.
19
+ * @param interval Minimum amount of milliseconds betweeen function calls.
20
+ * @returns The throttled function.
21
+ */
22
+ declare function throttle<F extends (this: any, ...args: any[]) => void>(fn: F, interval?: number): (this: ThisParameterType<F>, ...args: Parameters<F>) => void;
23
+ /**
24
+ * Compares values recursively.
25
+ * @param a First object or primitive.
26
+ * @param b Second object or primitive.
27
+ * @returns If both objects are equal or not.
28
+ */
29
+ declare function deepEqual(a: any, b: any): boolean;
30
+ /**
31
+ * Only allows a function to be called once. If called more than once, the stored result is returned.
32
+ * @param fn Function to limit.
33
+ * @returns The stored result of the function.
34
+ */
35
+ declare function once<F extends (this: any, ...args: any[]) => any>(fn: F): (this: ThisParameterType<F>, ...args: Parameters<F>) => ReturnType<F>;
36
+ /**
37
+ * Picks certain keys from an object.
38
+ * @param obj The object to pick keys from.
39
+ * @param keys The keys to pick from the object.
40
+ * @returns An object with only the specified keys.
41
+ */
42
+ declare function pick<T, K extends readonly (keyof T)[]>(obj: T, keys: K): Pick<T, K[number]>;
43
+ /**
44
+ * Excludes certain keys from an object.
45
+ * @param obj The object to exclude keys from.
46
+ * @param keys The keys to exclude.
47
+ * @returns An object with the specified keys excluded.
48
+ */
49
+ declare function omit<T extends Record<string, any>, K extends readonly (keyof T)[]>(obj: T, keys: K): Omit<T, K[number]>;
50
+ /**
51
+ * Retries an async function an amount of times with optional delay.
52
+ * @param fn The function to retry.
53
+ * @param attempts Number of attempts to run.
54
+ * @param delayMs Optional number of milliseconds to wait between tries.
55
+ * @returns Result of the function.
56
+ */
57
+ declare function retry<T>(fn: () => Promise<T>, attempts: number, delayMs?: number): Promise<T>;
58
+ /**
59
+ * no operation (like in assembly code)
60
+ */
61
+ declare const noop: () => void;
62
+ /**
63
+ * Executes a function and catches any errors and returns a tuple, similar to GoLang.
64
+ * @param fn The function to execute.
65
+ * @returns A tuple where:
66
+ * - The first element is the error if one was thrown, otherwise `null`.
67
+ * - The second element is the return value of `fn` if no error occurred.
68
+ * @example
69
+ * ```ts
70
+ * const [err, value] = tryCatch(() => JSON.parse('{"x":1}'));
71
+ * if (err) {
72
+ * console.error("uh oh", err);
73
+ * } else {
74
+ * console.log("value:", value);
75
+ * }
76
+ * ```
77
+ */
78
+ declare function tryCatch<T>(fn: () => T): [error: unknown] | [error: null, value: T];
79
+ /**
80
+ * A function to tap into a value.
81
+ * @param fn A function that takes a value.
82
+ * @returns The value passed into the function `fn`.
83
+ * @example
84
+ * ```ts
85
+ * const double = (x: number) => x * 2;
86
+ *
87
+ * const result = [1, 2, 3]
88
+ * .map(tap(x => console.log("before doubling:", x)))
89
+ * .map(double);
90
+ *
91
+ * console.log(result);
92
+ * ```
93
+ */
94
+ declare function tap<T>(fn: (v: T) => void): (v: T) => T;
95
+ /**
96
+ * A generator for creating number ranges.
97
+ * @param end An end value (exclusive) starting at 0 or an object with start, step and end values.
98
+ * start: The value to start at (inclusive).
99
+ * step: How far to increment in each iteration, can be negative, defaults to 1.
100
+ * end: The value to end at (exclusive).
101
+ * @example
102
+ * ```ts
103
+ * for (const i of range(5)) {
104
+ * console.log(i) //0, 1, 2, 3, 4
105
+ * }
106
+ *
107
+ * for (const i of range({
108
+ * start: 3,
109
+ * end: 10,
110
+ * step: 2
111
+ * })) {
112
+ * console.log(i) //3, 5, 7, 9
113
+ * }
114
+ *
115
+ * for (const i of range({
116
+ * start: 10,
117
+ * end: 3,
118
+ * step: -2
119
+ * })) {
120
+ * console.log(i) //10, 8, 6, 4
121
+ * }
122
+ * ```
123
+ */
124
+ declare function range(end: number | {
125
+ start?: number;
126
+ end: number;
127
+ step?: number;
128
+ }): Generator<number>;
129
+ /**
130
+ * Creates a generator that loops through an iterator indefinitely.
131
+ * @param iterable The iterator to loop over.
132
+ * @returns A looping generator using the iterator specified.
133
+ */
134
+ declare function cycle<T>(iterable: Iterable<T>): Generator<T>;
135
+ /**
136
+ * Breaks an array into chunks.
137
+ * @param arr The array to chunk.
138
+ * @param size Chunk size. (up to this value)
139
+ * @returns The chunked array.
140
+ */
141
+ declare function chunk<T>(arr: T[], size: number): T[][];
142
+ /**
143
+ * Shuffles an array.
144
+ * @param arr Array to shuffle.
145
+ * @returns Shuffled array.
146
+ */
147
+ declare function shuffle<T>(arr: T[]): T[];
148
+ /**
149
+ * Picks a random element from an array.
150
+ * @param arr Array to select from.
151
+ * @returns A random element from the specified array.
152
+ */
153
+ declare function sample<T>(arr: T[]): T | undefined;
154
+ /**
155
+ * Safely shifts an array by an amount.
156
+ * @param arr The array to rotate.
157
+ * @param n How much to shift by, and which way to shift; Positive ->, Negative <-.
158
+ * @returns Shifted (Rotated) array.
159
+ */
160
+ declare function rotate<T>(arr: T[], n: number): T[];
161
+
162
+ /**
163
+ * Returns a promise that resolves in a certain amount of milliseconds.
164
+ * Note: this won't be 100% accurate.
165
+ * @param ms The number of milliseconds to wait.
166
+ * @returns The promise.
167
+ */
168
+ declare function sleep(ms: number): Promise<void>;
169
+ declare class AsyncQueue {
170
+ private queue;
171
+ run<T>(fn: () => Promise<T>): Promise<T>;
172
+ }
173
+ /**
174
+ * Creates a deferred promise.
175
+ *
176
+ * Useful when the promise must be resolved or rejected from outside its executor.
177
+ *
178
+ * @returns An object containing:
179
+ * - `promise`: Promise<unknown>
180
+ * - `resolve`: (value: unknown) => void
181
+ * - `reject`: (reason?: any) => void
182
+ *
183
+ * @example
184
+ * const { promise, resolve, reject } = deferred();
185
+ * // `resolve('ok')` or `reject(new Error('fail'))` can be called later.
186
+ */
187
+ declare function deferred(): {
188
+ promise: Promise<unknown>;
189
+ resolve: (value: unknown) => void;
190
+ reject: (reason?: any) => void;
191
+ };
192
+ /**
193
+ * Limits a promise's waiting time with a timeout.
194
+ * @param promise The promise to time.
195
+ * @param ms How many milliseconds to wait before timing out.
196
+ * @param error The error to throw after the set delay.
197
+ * @returns The timed out promise.
198
+ */
199
+ declare function timeoutPromise<T>(promise: Promise<T>, ms: number, error?: Error): Promise<unknown>;
200
+
201
+ type ValueOf<T> = T[keyof T];
202
+ type Entries<T> = {
203
+ [K in keyof T]: [K, T[K]];
204
+ }[keyof T][];
205
+ type Mutable<T> = {
206
+ -readonly [K in keyof T]: T[K];
207
+ };
208
+ type DeepPartial<T> = {
209
+ [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K];
210
+ };
211
+ type DeepRequired<T> = {
212
+ [K in keyof T]-?: T[K] extends object ? DeepRequired<T[K]> : T[K];
213
+ };
214
+ type Nullable<T> = T | null | undefined;
215
+ type NonNullable<T> = T extends null | undefined ? never : T;
216
+ type TupleOf<T, N extends number, R extends T[] = []> = R["length"] extends N ? R : TupleOf<T, N, [T, ...R]>;
217
+ type Merge<A, B> = Omit<A, keyof B> & B;
218
+ type Flat<T> = {
219
+ [K in keyof T]: T[K];
220
+ };
221
+
222
+ type DurationBuilderLongBase = {
223
+ toMilliseconds(): number;
224
+ toSeconds(): number;
225
+ toMinutes(): number;
226
+ toHours(): number;
227
+ toDays(): number;
228
+ };
229
+ type DurationBuilderShortBase = {
230
+ toMs(): number;
231
+ toS(): number;
232
+ toM(): number;
233
+ toH(): number;
234
+ toD(): number;
235
+ };
236
+ type LongValues = {
237
+ milliseconds(v: number): DurationBuilderLong;
238
+ seconds(v: number): DurationBuilderLong;
239
+ minutes(v: number): DurationBuilderLong;
240
+ hours(v: number): DurationBuilderLong;
241
+ days(v: number): DurationBuilderLong;
242
+ };
243
+ type DurationBuilderLong = Flat<DurationBuilderLongBase & LongValues>;
244
+ type ShortValues = {
245
+ ms(v: number): DurationBuilderShort;
246
+ s(v: number): DurationBuilderShort;
247
+ m(v: number): DurationBuilderShort;
248
+ h(v: number): DurationBuilderShort;
249
+ d(v: number): DurationBuilderShort;
250
+ };
251
+ type DurationBuilderShort = Flat<DurationBuilderShortBase & ShortValues>;
252
+ declare const days: (v: number) => Flat<DurationBuilderLongBase & LongValues>;
253
+ declare const hours: (v: number) => Flat<DurationBuilderLongBase & LongValues>;
254
+ declare const minutes: (v: number) => Flat<DurationBuilderLongBase & LongValues>;
255
+ declare const seconds: (v: number) => Flat<DurationBuilderLongBase & LongValues>;
256
+ declare const milliseconds: (v: number) => Flat<DurationBuilderLongBase & LongValues>;
257
+ declare const d: (v: number) => Flat<DurationBuilderShortBase & ShortValues>;
258
+ declare const h: (v: number) => Flat<DurationBuilderShortBase & ShortValues>;
259
+ declare const m: (v: number) => Flat<DurationBuilderShortBase & ShortValues>;
260
+ declare const s: (v: number) => Flat<DurationBuilderShortBase & ShortValues>;
261
+ declare const ms: (v: number) => Flat<DurationBuilderShortBase & ShortValues>;
262
+
263
+ /**
264
+ * BigInt Exponent Operation.
265
+ * @param one The base.
266
+ * @param two The exponent.
267
+ * @returns The bigint result of `one` to the power of `two`.
268
+ */
269
+ declare function bigIntPower(one: bigint, two: bigint): bigint;
270
+ /**
271
+ * Converts numbers between bases. (e.g. hexadecimal to binary)
272
+ * @param value The value to convert.
273
+ * @param sourceBase The base of value.
274
+ * @param outBase The result's base.
275
+ * @param chars The characters to use, defaults to `convertBase.defaultChars`.
276
+ * @returns The resulting value in specified base using the specified characters.
277
+ */
278
+ declare function convertBase(value: string, sourceBase: number, outBase: number, chars?: string): string;
279
+ declare namespace convertBase {
280
+ var defaultChars: string;
281
+ var MAX_BASE: number;
282
+ }
283
+ /**
284
+ * Clamps a number between min and max.
285
+ * @param number The number to clamp.
286
+ * @param min The minimum number.
287
+ * @param max The maximum number.
288
+ * @returns The number clamped to the range specified.
289
+ */
290
+ declare function clamp(number: number, min: number, max: number): number;
291
+ /**
292
+ * Returns a random integer between min and max
293
+ * @param min The minimum number.
294
+ * @param max The maximum number. Exclusive by default, like Java's `Math.Random()`.
295
+ * @param inclusive Determines whether the `max` is included or excluded from the range.
296
+ * @returns A random number within the range specified.
297
+ */
298
+ declare function randInt(min: number, max: number, inclusive?: boolean): number;
299
+ /**
300
+ * Returns true approximately (probablity * 100)% of the time
301
+ * @param probability Number between 0 and 1.
302
+ * @returns A boolean averaging the probability specified.
303
+ */
304
+ declare function chance(probability: number): boolean;
305
+ /**
306
+ * Rounds a number to a certain number of decimals.
307
+ * @param n The number to round.
308
+ * @param decimals The number of places.
309
+ * @returns Number rounded to specified places.
310
+ * @example
311
+ * ```ts
312
+ * console.log(roundTo(Math.PI, 5));
313
+ * ```
314
+ * shows as `3.14159` in the console.
315
+ */
316
+ declare function roundTo(n: number, decimals: number): number;
317
+ /**
318
+ * Interpolates between a and b.
319
+ * @param a
320
+ * @param b
321
+ * @param t
322
+ * @returns
323
+ */
324
+ declare function lerp(a: number, b: number, t: number): number;
325
+ /**
326
+ * Determines if a value is in a range.
327
+ * @param n The number to check for in a range.
328
+ * @param min The minimum of the range.
329
+ * @param max The maximum of the range.
330
+ * @returns If the number is in the specified range.
331
+ */
332
+ declare function inRange(n: number, min: number, max: number): boolean;
333
+
334
+ /**
335
+ * A map with time-limited keys.
336
+ * Keys are deleted after a set amount of time.
337
+ */
338
+ declare class TimedMap<K, V> {
339
+ private defaultTtlMs?;
340
+ private map;
341
+ private timers;
342
+ constructor(defaultTtlMs?: number | undefined);
343
+ set(key: K, value: V, ttlMs?: number | undefined): void;
344
+ has(key: K): boolean;
345
+ clear(): void;
346
+ get(key: K): V | undefined;
347
+ delete(key: K): boolean;
348
+ get size(): number;
349
+ }
350
+ /**
351
+ * A map with access based expiration.
352
+ * Keys are deleted after a set amount of time without access.
353
+ */
354
+ declare class AccessMap<K, V> {
355
+ private defaultTtlMs?;
356
+ private map;
357
+ private timers;
358
+ constructor(defaultTtlMs?: number | undefined);
359
+ set(key: K, value: V, ttlMs?: number | undefined): void;
360
+ has(key: K): boolean;
361
+ clear(): void;
362
+ get(key: K): V | undefined;
363
+ delete(key: K): boolean;
364
+ get size(): number;
365
+ private resetTimer;
366
+ }
367
+
368
+ export { AccessMap, AsyncQueue, type DebouncedFunction, type DeepPartial, type DeepRequired, type Entries, type Flat, type Merge, type Mutable, type NonNullable, type Nullable, TimedMap, type TupleOf, type ValueOf, bigIntPower, chance, chunk, clamp, convertBase, cycle, d, days, debounce, deepEqual, deferred, h, hours, inRange, lerp, m, milliseconds, minutes, ms, noop, omit, once, pick, randInt, range, retry, rotate, roundTo, s, sample, seconds, shuffle, sleep, tap, throttle, timeoutPromise, tryCatch };