Commit | Line | Data |
---|---|---|
c37528f1 | 1 | import crypto from 'crypto'; |
6af9012e | 2 | import { v4 as uuid } from 'uuid'; |
7dde0b73 | 3 | |
3f40bc9c | 4 | export default class Utils { |
0f16a662 | 5 | public static logPrefix(prefixString = ''): string { |
147d0e0f JB |
6 | return new Date().toLocaleString() + prefixString; |
7 | } | |
8 | ||
0f16a662 | 9 | public static generateUUID(): string { |
2e3ac96d | 10 | return uuid(); |
7dde0b73 JB |
11 | } |
12 | ||
0f16a662 | 13 | public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> { |
5f8a4fd6 | 14 | return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds)); |
7dde0b73 JB |
15 | } |
16 | ||
d7d1db72 JB |
17 | public static formatDurationMilliSeconds(duration: number): string { |
18 | duration = Utils.convertToInt(duration); | |
19 | const hours = Math.floor(duration / (3600 * 1000)); | |
e7aeea18 JB |
20 | const minutes = Math.floor((duration / 1000 - hours * 3600) / 60); |
21 | const seconds = duration / 1000 - hours * 3600 - minutes * 60; | |
a3868ec4 JB |
22 | let hoursStr = hours.toString(); |
23 | let minutesStr = minutes.toString(); | |
24 | let secondsStr = seconds.toString(); | |
d7d1db72 JB |
25 | |
26 | if (hours < 10) { | |
27 | hoursStr = '0' + hours.toString(); | |
28 | } | |
29 | if (minutes < 10) { | |
30 | minutesStr = '0' + minutes.toString(); | |
31 | } | |
32 | if (seconds < 10) { | |
b322b8b4 | 33 | secondsStr = '0' + seconds.toString(); |
d7d1db72 | 34 | } |
b322b8b4 | 35 | return hoursStr + ':' + minutesStr + ':' + secondsStr.substring(0, 6); |
9ac86a7e JB |
36 | } |
37 | ||
d7d1db72 JB |
38 | public static formatDurationSeconds(duration: number): string { |
39 | return Utils.formatDurationMilliSeconds(duration * 1000); | |
7dde0b73 JB |
40 | } |
41 | ||
0f16a662 | 42 | public static convertToDate(value: unknown): Date { |
560bcf5b | 43 | // Check |
6af9012e | 44 | if (!value) { |
73d09045 | 45 | return value as Date; |
560bcf5b JB |
46 | } |
47 | // Check Type | |
6af9012e | 48 | if (!(value instanceof Date)) { |
73d09045 | 49 | return new Date(value as string); |
7dde0b73 | 50 | } |
6af9012e | 51 | return value; |
7dde0b73 JB |
52 | } |
53 | ||
0f16a662 | 54 | public static convertToInt(value: unknown): number { |
73d09045 | 55 | let changedValue: number = value as number; |
72766a82 | 56 | if (!value) { |
7dde0b73 JB |
57 | return 0; |
58 | } | |
72766a82 | 59 | if (Number.isSafeInteger(value)) { |
95926c9b | 60 | return value as number; |
72766a82 | 61 | } |
7dde0b73 | 62 | // Check |
087a502d | 63 | if (Utils.isString(value)) { |
7dde0b73 | 64 | // Create Object |
73d09045 | 65 | changedValue = parseInt(value as string); |
7dde0b73 | 66 | } |
72766a82 | 67 | return changedValue; |
7dde0b73 JB |
68 | } |
69 | ||
0f16a662 | 70 | public static convertToFloat(value: unknown): number { |
73d09045 | 71 | let changedValue: number = value as number; |
72766a82 | 72 | if (!value) { |
7dde0b73 JB |
73 | return 0; |
74 | } | |
75 | // Check | |
087a502d | 76 | if (Utils.isString(value)) { |
7dde0b73 | 77 | // Create Object |
73d09045 | 78 | changedValue = parseFloat(value as string); |
7dde0b73 | 79 | } |
72766a82 | 80 | return changedValue; |
7dde0b73 JB |
81 | } |
82 | ||
0f16a662 | 83 | public static convertToBoolean(value: unknown): boolean { |
a6e68f34 JB |
84 | let result = false; |
85 | // Check boolean | |
86 | if (value) { | |
87 | // Check the type | |
88 | if (typeof value === 'boolean') { | |
89 | // Already a boolean | |
90 | result = value; | |
91 | } else { | |
92 | // Convert | |
e7aeea18 | 93 | result = value === 'true'; |
a6e68f34 JB |
94 | } |
95 | } | |
96 | return result; | |
97 | } | |
98 | ||
fd00fa2e | 99 | public static getRandomFloat(max: number, min = 0, negative = false): number { |
b322b8b4 JB |
100 | if (max < min || min < 0 || max < 0) { |
101 | throw new RangeError('Invalid interval'); | |
102 | } | |
fd00fa2e | 103 | const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff; |
e7aeea18 | 104 | const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1; |
fd00fa2e | 105 | return sign * (randomPositiveFloat * (max - min) + min); |
560bcf5b JB |
106 | } |
107 | ||
72740232 | 108 | public static getRandomInteger(max: number, min = 0): number { |
a3868ec4 JB |
109 | if (max < 0) { |
110 | throw new RangeError('Invalid interval'); | |
111 | } | |
fd00fa2e | 112 | max = Math.floor(max); |
7dde0b73 | 113 | if (min) { |
a3868ec4 JB |
114 | if (max < min || min < 0) { |
115 | throw new RangeError('Invalid interval'); | |
116 | } | |
fd00fa2e | 117 | min = Math.ceil(min); |
c37528f1 | 118 | return Math.floor(Utils.secureRandom() * (max - min + 1)) + min; |
7dde0b73 | 119 | } |
c37528f1 | 120 | return Math.floor(Utils.secureRandom() * (max + 1)); |
560bcf5b JB |
121 | } |
122 | ||
0f16a662 | 123 | public static roundTo(numberValue: number, scale: number): number { |
ad3de6c4 | 124 | const roundPower = Math.pow(10, scale); |
035742f7 | 125 | return Math.round(numberValue * roundPower) / roundPower; |
560bcf5b JB |
126 | } |
127 | ||
0f16a662 | 128 | public static truncTo(numberValue: number, scale: number): number { |
6d3a11a0 | 129 | const truncPower = Math.pow(10, scale); |
035742f7 | 130 | return Math.trunc(numberValue * truncPower) / truncPower; |
6d3a11a0 JB |
131 | } |
132 | ||
0f16a662 | 133 | public static getRandomFloatRounded(max: number, min = 0, scale = 2): number { |
560bcf5b JB |
134 | if (min) { |
135 | return Utils.roundTo(Utils.getRandomFloat(max, min), scale); | |
136 | } | |
137 | return Utils.roundTo(Utils.getRandomFloat(max), scale); | |
7dde0b73 JB |
138 | } |
139 | ||
e7aeea18 JB |
140 | public static getRandomFloatFluctuatedRounded( |
141 | staticValue: number, | |
142 | fluctuationPercent: number, | |
143 | scale = 2 | |
144 | ): number { | |
9ccca265 JB |
145 | if (fluctuationPercent === 0) { |
146 | return Utils.roundTo(staticValue, scale); | |
147 | } | |
97ef739c | 148 | const fluctuationRatio = fluctuationPercent / 100; |
e7aeea18 JB |
149 | return Utils.getRandomFloatRounded( |
150 | staticValue * (1 + fluctuationRatio), | |
151 | staticValue * (1 - fluctuationRatio), | |
152 | scale | |
153 | ); | |
9ccca265 JB |
154 | } |
155 | ||
0f16a662 | 156 | public static cloneObject<T>(object: T): T { |
e56aa9a4 | 157 | return JSON.parse(JSON.stringify(object)) as T; |
2e6f5966 | 158 | } |
facd8ebd | 159 | |
0f16a662 | 160 | public static isIterable<T>(obj: T): boolean { |
7558b3a6 | 161 | return obj ? typeof obj[Symbol.iterator] === 'function' : false; |
67e9cccf JB |
162 | } |
163 | ||
0f16a662 | 164 | public static isString(value: unknown): boolean { |
560bcf5b JB |
165 | return typeof value === 'string'; |
166 | } | |
167 | ||
e8191622 JB |
168 | public static isEmptyString(value: unknown): boolean { |
169 | return Utils.isString(value) && (value as string).length === 0; | |
170 | } | |
171 | ||
0f16a662 | 172 | public static isUndefined(value: unknown): boolean { |
ead548f2 JB |
173 | return typeof value === 'undefined'; |
174 | } | |
175 | ||
0f16a662 | 176 | public static isNullOrUndefined(value: unknown): boolean { |
7558b3a6 JB |
177 | // eslint-disable-next-line eqeqeq, no-eq-null |
178 | return value == null ? true : false; | |
facd8ebd | 179 | } |
4a56deef | 180 | |
0f16a662 | 181 | public static isEmptyArray(object: unknown): boolean { |
fd1ee77c JB |
182 | if (!object) { |
183 | return true; | |
184 | } | |
4a56deef JB |
185 | if (Array.isArray(object) && object.length > 0) { |
186 | return false; | |
187 | } | |
188 | return true; | |
189 | } | |
7abfea5f | 190 | |
94ec7e96 | 191 | public static isEmptyObject(obj: object): boolean { |
7abfea5f JB |
192 | return !Object.keys(obj).length; |
193 | } | |
7ec46a9a | 194 | |
e7aeea18 JB |
195 | public static insertAt = (str: string, subStr: string, pos: number): string => |
196 | `${str.slice(0, pos)}${subStr}${str.slice(pos)}`; | |
032d6efc JB |
197 | |
198 | /** | |
81797102 JB |
199 | * @param [retryNumber=0] |
200 | * @returns delay in milliseconds | |
032d6efc | 201 | */ |
0f16a662 | 202 | public static exponentialDelay(retryNumber = 0): number { |
032d6efc | 203 | const delay = Math.pow(2, retryNumber) * 100; |
c37528f1 | 204 | const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay |
032d6efc JB |
205 | return delay + randomSum; |
206 | } | |
32a1eb7a | 207 | |
6d9abcc2 | 208 | public static async promiseWithTimeout<T>( |
e7aeea18 JB |
209 | promise: Promise<T>, |
210 | timeoutMs: number, | |
211 | timeoutError: Error, | |
212 | timeoutCallback: () => void = () => { | |
213 | /* This is intentional */ | |
214 | } | |
6d9abcc2 JB |
215 | ): Promise<T> { |
216 | // Create a timeout promise that rejects in timeout milliseconds | |
217 | const timeoutPromise = new Promise<never>((_, reject) => { | |
218 | setTimeout(() => { | |
ed0f8380 | 219 | timeoutCallback(); |
6d9abcc2 JB |
220 | reject(timeoutError); |
221 | }, timeoutMs); | |
222 | }); | |
223 | ||
224 | // Returns a race between timeout promise and the passed promise | |
225 | return Promise.race<T>([promise, timeoutPromise]); | |
226 | } | |
227 | ||
c37528f1 | 228 | /** |
0f16a662 | 229 | * Generate a cryptographically secure random number in the [0,1[ range |
c37528f1 JB |
230 | * |
231 | * @returns | |
232 | */ | |
0f16a662 | 233 | public static secureRandom(): number { |
c37528f1 JB |
234 | return crypto.randomBytes(4).readUInt32LE() / 0x100000000; |
235 | } | |
7dde0b73 | 236 | } |