refactor: cleanup null checks and helpers
[e-mobility-charging-stations-simulator.git] / ui / web / src / composables / Utils.ts
CommitLineData
2eb6954d
JB
1import util from 'node:util';
2
f568f368
JB
3const isUndefined = (value: unknown): boolean => {
4 return typeof value === 'undefined';
5};
6
7export 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
23const isPromisePending = (promise: Promise<unknown>): boolean => {
24 return util.inspect(promise).includes('pending');
25};
26
27export const promiseWithTimeout = <T>(
28 promise: Promise<T>,
29 timeoutMs: number,
30 timeoutError: Error,
31 timeoutCallback: () => void = () => {
32 /* This is intentional */
32de5a57 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// };