Commit | Line | Data |
---|---|---|
2eb6954d JB |
1 | import util from 'node:util'; |
2 | ||
f568f368 JB |
3 | const isUndefined = (value: unknown): boolean => { |
4 | return typeof value === 'undefined'; | |
5 | }; | |
6 | ||
7 | export const ifUndefined = <T>(value: T | undefined, isValue: T): T => { | |
8 | if (isUndefined(value) === true) return isValue; | |
9 | return value as T; | |
10 | }; | |
11 | ||
12 | // const isIterable = <T>(obj: T): boolean => { | |
13 | // if (obj === null || obj === undefined) { | |
14 | // return false; | |
15 | // } | |
16 | // return typeof (obj as unknown as Iterable<T>)[Symbol.iterator] === 'function'; | |
17 | // }; | |
18 | ||
19 | // const ifNotIterableDo = <T>(obj: T, cb: () => void): void => { | |
20 | // if (isIterable(obj) === false) cb(); | |
21 | // }; | |
22 | ||
23 | const isPromisePending = (promise: Promise<unknown>): boolean => { | |
24 | return util.inspect(promise).includes('pending'); | |
25 | }; | |
26 | ||
27 | export const promiseWithTimeout = <T>( | |
28 | promise: Promise<T>, | |
29 | timeoutMs: number, | |
30 | timeoutError: Error, | |
31 | timeoutCallback: () => void = () => { | |
32 | /* This is intentional */ | |
f3095697 | 33 | }, |
f568f368 JB |
34 | ): Promise<T> => { |
35 | // Create a timeout promise that rejects in timeout milliseconds | |
36 | const timeoutPromise = new Promise<never>((_, reject) => { | |
37 | setTimeout(() => { | |
38 | if (isPromisePending(promise)) { | |
39 | timeoutCallback(); | |
40 | // FIXME: The original promise shall be canceled | |
41 | } | |
42 | reject(timeoutError); | |
43 | }, timeoutMs); | |
44 | }); | |
45 | ||
46 | // Returns a race between timeout promise and the passed promise | |
47 | return Promise.race<T>([promise, timeoutPromise]); | |
48 | }; | |
49 | ||
50 | // export const compose = <T>(...fns: ((arg: T) => T)[]): ((x: T) => T) => { | |
51 | // return (x: T) => fns.reduceRight((y, fn) => fn(y), x); | |
52 | // }; |