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