1 import crypto from
'crypto';
3 import { v4
as uuid
} from
'uuid';
5 export default class Utils
{
6 private constructor() {
10 public static logPrefix(prefixString
= ''): string {
11 return new Date().toLocaleString() + prefixString
;
14 public static generateUUID(): string {
18 public static async sleep(milliSeconds
: number): Promise
<NodeJS
.Timeout
> {
19 return new Promise((resolve
) => setTimeout(resolve
as () => void, milliSeconds
));
22 public static formatDurationMilliSeconds(duration
: number): string {
23 duration
= Utils
.convertToInt(duration
);
24 const hours
= Math.floor(duration
/ (3600 * 1000));
25 const minutes
= Math.floor((duration
/ 1000 - hours
* 3600) / 60);
26 const seconds
= duration
/ 1000 - hours
* 3600 - minutes
* 60;
27 let hoursStr
= hours
.toString();
28 let minutesStr
= minutes
.toString();
29 let secondsStr
= seconds
.toString();
32 hoursStr
= '0' + hours
.toString();
35 minutesStr
= '0' + minutes
.toString();
38 secondsStr
= '0' + seconds
.toString();
40 return hoursStr
+ ':' + minutesStr
+ ':' + secondsStr
.substring(0, 6);
43 public static formatDurationSeconds(duration
: number): string {
44 return Utils
.formatDurationMilliSeconds(duration
* 1000);
47 public static convertToDate(value
: unknown
): Date {
53 if (!(value
instanceof Date)) {
54 return new Date(value
as string);
59 public static convertToInt(value
: unknown
): number {
60 let changedValue
: number = value
as number;
64 if (Number.isSafeInteger(value
)) {
65 return value
as number;
68 if (Utils
.isString(value
)) {
70 changedValue
= parseInt(value
as string);
75 public static convertToFloat(value
: unknown
): number {
76 let changedValue
: number = value
as number;
81 if (Utils
.isString(value
)) {
83 changedValue
= parseFloat(value
as string);
88 public static convertToBoolean(value
: unknown
): boolean {
93 if (typeof value
=== 'boolean') {
98 result
= value
=== 'true';
104 public static getRandomFloat(max
: number, min
= 0, negative
= false): number {
105 if (max
< min
|| min
< 0 || max
< 0) {
106 throw new RangeError('Invalid interval');
108 const randomPositiveFloat
= crypto
.randomBytes(4).readUInt32LE() / 0xffffffff;
109 const sign
= negative
&& randomPositiveFloat
< 0.5 ? -1 : 1;
110 return sign
* (randomPositiveFloat
* (max
- min
) + min
);
113 public static getRandomInteger(max
: number, min
= 0): number {
115 throw new RangeError('Invalid interval');
117 max
= Math.floor(max
);
119 if (max
< min
|| min
< 0) {
120 throw new RangeError('Invalid interval');
122 min
= Math.ceil(min
);
123 return Math.floor(Utils
.secureRandom() * (max
- min
+ 1)) + min
;
125 return Math.floor(Utils
.secureRandom() * (max
+ 1));
128 public static roundTo(numberValue
: number, scale
: number): number {
129 const roundPower
= Math.pow(10, scale
);
130 return Math.round(numberValue
* roundPower
) / roundPower
;
133 public static truncTo(numberValue
: number, scale
: number): number {
134 const truncPower
= Math.pow(10, scale
);
135 return Math.trunc(numberValue
* truncPower
) / truncPower
;
138 public static getRandomFloatRounded(max
: number, min
= 0, scale
= 2): number {
140 return Utils
.roundTo(Utils
.getRandomFloat(max
, min
), scale
);
142 return Utils
.roundTo(Utils
.getRandomFloat(max
), scale
);
145 public static getRandomFloatFluctuatedRounded(
147 fluctuationPercent
: number,
150 if (fluctuationPercent
=== 0) {
151 return Utils
.roundTo(staticValue
, scale
);
153 const fluctuationRatio
= fluctuationPercent
/ 100;
154 return Utils
.getRandomFloatRounded(
155 staticValue
* (1 + fluctuationRatio
),
156 staticValue
* (1 - fluctuationRatio
),
161 public static cloneObject
<T
>(object
: T
): T
{
162 return JSON
.parse(JSON
.stringify(object
)) as T
;
165 public static isIterable
<T
>(obj
: T
): boolean {
166 return obj
? typeof obj
[Symbol
.iterator
] === 'function' : false;
169 public static isString(value
: unknown
): boolean {
170 return typeof value
=== 'string';
173 public static isEmptyString(value
: unknown
): boolean {
174 return Utils
.isString(value
) && (value
as string).length
=== 0;
177 public static isUndefined(value
: unknown
): boolean {
178 return typeof value
=== 'undefined';
181 public static isNullOrUndefined(value
: unknown
): boolean {
182 // eslint-disable-next-line eqeqeq, no-eq-null
183 return value
== null ? true : false;
186 public static isEmptyArray(object
: unknown
): boolean {
190 if (Array.isArray(object
) && object
.length
> 0) {
196 public static isEmptyObject(obj
: object
): boolean {
197 return !Object.keys(obj
).length
;
200 public static insertAt
= (str
: string, subStr
: string, pos
: number): string =>
201 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
204 * @param [retryNumber=0]
205 * @returns delay in milliseconds
207 public static exponentialDelay(retryNumber
= 0): number {
208 const delay
= Math.pow(2, retryNumber
) * 100;
209 const randomSum
= delay
* 0.2 * Utils
.secureRandom(); // 0-20% of the delay
210 return delay
+ randomSum
;
213 public static async promiseWithTimeout
<T
>(
217 timeoutCallback
: () => void = () => {
218 /* This is intentional */
221 // Create a timeout promise that rejects in timeout milliseconds
222 const timeoutPromise
= new Promise
<never>((_
, reject
) => {
225 reject(timeoutError
);
229 // Returns a race between timeout promise and the passed promise
230 return Promise
.race
<T
>([promise
, timeoutPromise
]);
234 * Generate a cryptographically secure random number in the [0,1[ range
238 public static secureRandom(): number {
239 return crypto
.randomBytes(4).readUInt32LE() / 0x100000000;