1 import crypto from
'crypto';
2 import { v4
as uuid
} from
'uuid';
4 export default class Utils
{
5 public static logPrefix(prefixString
= ''): string {
6 return new Date().toLocaleString() + prefixString
;
9 public static generateUUID(): string {
13 public static async sleep(milliSeconds
: number): Promise
<NodeJS
.Timeout
> {
14 return new Promise((resolve
) => setTimeout(resolve
as () => void, milliSeconds
));
17 public static formatDurationMilliSeconds(duration
: number): string {
18 duration
= Utils
.convertToInt(duration
);
19 const hours
= Math.floor(duration
/ (3600 * 1000));
20 const minutes
= Math.floor((duration
/ 1000 - hours
* 3600) / 60);
21 const seconds
= duration
/ 1000 - hours
* 3600 - minutes
* 60;
22 let hoursStr
= hours
.toString();
23 let minutesStr
= minutes
.toString();
24 let secondsStr
= seconds
.toString();
27 hoursStr
= '0' + hours
.toString();
30 minutesStr
= '0' + minutes
.toString();
33 secondsStr
= '0' + seconds
.toString();
35 return hoursStr
+ ':' + minutesStr
+ ':' + secondsStr
.substring(0, 6);
38 public static formatDurationSeconds(duration
: number): string {
39 return Utils
.formatDurationMilliSeconds(duration
* 1000);
42 public static convertToDate(value
: unknown
): Date {
48 if (!(value
instanceof Date)) {
49 return new Date(value
as string);
54 public static convertToInt(value
: unknown
): number {
55 let changedValue
: number = value
as number;
59 if (Number.isSafeInteger(value
)) {
60 return value
as number;
63 if (Utils
.isString(value
)) {
65 changedValue
= parseInt(value
as string);
70 public static convertToFloat(value
: unknown
): number {
71 let changedValue
: number = value
as number;
76 if (Utils
.isString(value
)) {
78 changedValue
= parseFloat(value
as string);
83 public static convertToBoolean(value
: unknown
): boolean {
88 if (typeof value
=== 'boolean') {
93 result
= value
=== 'true';
99 public static getRandomFloat(max
: number, min
= 0, negative
= false): number {
100 if (max
< min
|| min
< 0 || max
< 0) {
101 throw new RangeError('Invalid interval');
103 const randomPositiveFloat
= crypto
.randomBytes(4).readUInt32LE() / 0xffffffff;
104 const sign
= negative
&& randomPositiveFloat
< 0.5 ? -1 : 1;
105 return sign
* (randomPositiveFloat
* (max
- min
) + min
);
108 public static getRandomInteger(max
: number, min
= 0): number {
110 throw new RangeError('Invalid interval');
112 max
= Math.floor(max
);
114 if (max
< min
|| min
< 0) {
115 throw new RangeError('Invalid interval');
117 min
= Math.ceil(min
);
118 return Math.floor(Utils
.secureRandom() * (max
- min
+ 1)) + min
;
120 return Math.floor(Utils
.secureRandom() * (max
+ 1));
123 public static roundTo(numberValue
: number, scale
: number): number {
124 const roundPower
= Math.pow(10, scale
);
125 return Math.round(numberValue
* roundPower
) / roundPower
;
128 public static truncTo(numberValue
: number, scale
: number): number {
129 const truncPower
= Math.pow(10, scale
);
130 return Math.trunc(numberValue
* truncPower
) / truncPower
;
133 public static getRandomFloatRounded(max
: number, min
= 0, scale
= 2): number {
135 return Utils
.roundTo(Utils
.getRandomFloat(max
, min
), scale
);
137 return Utils
.roundTo(Utils
.getRandomFloat(max
), scale
);
140 public static getRandomFloatFluctuatedRounded(
142 fluctuationPercent
: number,
145 if (fluctuationPercent
=== 0) {
146 return Utils
.roundTo(staticValue
, scale
);
148 const fluctuationRatio
= fluctuationPercent
/ 100;
149 return Utils
.getRandomFloatRounded(
150 staticValue
* (1 + fluctuationRatio
),
151 staticValue
* (1 - fluctuationRatio
),
156 public static cloneObject
<T
>(object
: T
): T
{
157 return JSON
.parse(JSON
.stringify(object
)) as T
;
160 public static isIterable
<T
>(obj
: T
): boolean {
161 return obj
? typeof obj
[Symbol
.iterator
] === 'function' : false;
164 public static isString(value
: unknown
): boolean {
165 return typeof value
=== 'string';
168 public static isEmptyString(value
: unknown
): boolean {
169 return Utils
.isString(value
) && (value
as string).length
=== 0;
172 public static isUndefined(value
: unknown
): boolean {
173 return typeof value
=== 'undefined';
176 public static isNullOrUndefined(value
: unknown
): boolean {
177 // eslint-disable-next-line eqeqeq, no-eq-null
178 return value
== null ? true : false;
181 public static isEmptyArray(object
: unknown
): boolean {
185 if (Array.isArray(object
) && object
.length
> 0) {
191 public static isEmptyObject(obj
: object
): boolean {
192 return !Object.keys(obj
).length
;
195 public static insertAt
= (str
: string, subStr
: string, pos
: number): string =>
196 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
199 * @param [retryNumber=0]
200 * @returns delay in milliseconds
202 public static exponentialDelay(retryNumber
= 0): number {
203 const delay
= Math.pow(2, retryNumber
) * 100;
204 const randomSum
= delay
* 0.2 * Utils
.secureRandom(); // 0-20% of the delay
205 return delay
+ randomSum
;
208 public static async promiseWithTimeout
<T
>(
212 timeoutCallback
: () => void = () => {
213 /* This is intentional */
216 // Create a timeout promise that rejects in timeout milliseconds
217 const timeoutPromise
= new Promise
<never>((_
, reject
) => {
220 reject(timeoutError
);
224 // Returns a race between timeout promise and the passed promise
225 return Promise
.race
<T
>([promise
, timeoutPromise
]);
229 * Generate a cryptographically secure random number in the [0,1[ range
233 public static secureRandom(): number {
234 return crypto
.randomBytes(4).readUInt32LE() / 0x100000000;