1 import crypto from
'crypto';
3 import { v4
as uuid
} from
'uuid';
5 import { WebSocketCloseEventStatusString
} from
'../types/WebSocket';
7 export default class Utils
{
8 private constructor() {
12 public static logPrefix(prefixString
= ''): string {
13 return new Date().toLocaleString() + prefixString
;
16 public static generateUUID(): string {
20 public static async sleep(milliSeconds
: number): Promise
<NodeJS
.Timeout
> {
21 return new Promise((resolve
) => setTimeout(resolve
as () => void, milliSeconds
));
24 public static formatDurationMilliSeconds(duration
: number): string {
25 duration
= Utils
.convertToInt(duration
);
26 const hours
= Math.floor(duration
/ (3600 * 1000));
27 const minutes
= Math.floor((duration
/ 1000 - hours
* 3600) / 60);
28 const seconds
= duration
/ 1000 - hours
* 3600 - minutes
* 60;
29 let hoursStr
= hours
.toString();
30 let minutesStr
= minutes
.toString();
31 let secondsStr
= seconds
.toString();
34 hoursStr
= '0' + hours
.toString();
37 minutesStr
= '0' + minutes
.toString();
40 secondsStr
= '0' + seconds
.toString();
42 return hoursStr
+ ':' + minutesStr
+ ':' + secondsStr
.substring(0, 6);
45 public static formatDurationSeconds(duration
: number): string {
46 return Utils
.formatDurationMilliSeconds(duration
* 1000);
49 public static convertToDate(value
: unknown
): Date {
55 if (!(value
instanceof Date)) {
56 return new Date(value
as string);
61 public static convertToInt(value
: unknown
): number {
62 let changedValue
: number = value
as number;
66 if (Number.isSafeInteger(value
)) {
67 return value
as number;
70 if (Utils
.isString(value
)) {
72 changedValue
= parseInt(value
as string);
77 public static convertToFloat(value
: unknown
): number {
78 let changedValue
: number = value
as number;
83 if (Utils
.isString(value
)) {
85 changedValue
= parseFloat(value
as string);
90 public static convertToBoolean(value
: unknown
): boolean {
95 if (typeof value
=== 'boolean') {
100 result
= value
=== 'true';
106 public static getRandomFloat(max
= Number.MAX_VALUE
, min
= 0, negative
= false): number {
107 if (max
< min
|| min
< 0 || max
< 0) {
108 throw new RangeError('Invalid interval');
110 const randomPositiveFloat
= crypto
.randomBytes(4).readUInt32LE() / 0xffffffff;
111 const sign
= negative
&& randomPositiveFloat
< 0.5 ? -1 : 1;
112 return sign
* (randomPositiveFloat
* (max
- min
) + min
);
115 public static getRandomInteger(max
= Number.MAX_SAFE_INTEGER
, min
= 0): number {
117 throw new RangeError('Invalid interval');
119 max
= Math.floor(max
);
121 if (max
< min
|| min
< 0) {
122 throw new RangeError('Invalid interval');
124 min
= Math.ceil(min
);
125 return Math.floor(Utils
.secureRandom() * (max
- min
+ 1)) + min
;
127 return Math.floor(Utils
.secureRandom() * (max
+ 1));
130 public static roundTo(numberValue
: number, scale
: number): number {
131 const roundPower
= Math.pow(10, scale
);
132 return Math.round(numberValue
* roundPower
) / roundPower
;
135 public static truncTo(numberValue
: number, scale
: number): number {
136 const truncPower
= Math.pow(10, scale
);
137 return Math.trunc(numberValue
* truncPower
) / truncPower
;
140 public static getRandomFloatRounded(max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number {
142 return Utils
.roundTo(Utils
.getRandomFloat(max
, min
), scale
);
144 return Utils
.roundTo(Utils
.getRandomFloat(max
), scale
);
147 public static getRandomFloatFluctuatedRounded(
149 fluctuationPercent
: number,
152 if (fluctuationPercent
=== 0) {
153 return Utils
.roundTo(staticValue
, scale
);
155 const fluctuationRatio
= fluctuationPercent
/ 100;
156 return Utils
.getRandomFloatRounded(
157 staticValue
* (1 + fluctuationRatio
),
158 staticValue
* (1 - fluctuationRatio
),
163 public static cloneObject
<T
>(object
: T
): T
{
164 return JSON
.parse(JSON
.stringify(object
)) as T
;
167 public static isIterable
<T
>(obj
: T
): boolean {
168 return obj
? typeof obj
[Symbol
.iterator
] === 'function' : false;
171 public static isString(value
: unknown
): boolean {
172 return typeof value
=== 'string';
175 public static isEmptyString(value
: unknown
): boolean {
176 return Utils
.isString(value
) && (value
as string).length
=== 0;
179 public static isUndefined(value
: unknown
): boolean {
180 return typeof value
=== 'undefined';
183 public static isNullOrUndefined(value
: unknown
): boolean {
184 // eslint-disable-next-line eqeqeq, no-eq-null
185 return value
== null ? true : false;
188 public static isEmptyArray(object
: unknown
): boolean {
192 if (Array.isArray(object
) === true && (object
as unknown
[]).length
> 0) {
198 public static isEmptyObject(obj
: object
): boolean {
199 return !Object.keys(obj
).length
;
202 public static insertAt
= (str
: string, subStr
: string, pos
: number): string =>
203 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
206 * @param [retryNumber=0]
207 * @returns delay in milliseconds
209 public static exponentialDelay(retryNumber
= 0): number {
210 const delay
= Math.pow(2, retryNumber
) * 100;
211 const randomSum
= delay
* 0.2 * Utils
.secureRandom(); // 0-20% of the delay
212 return delay
+ randomSum
;
215 public static async promiseWithTimeout
<T
>(
219 timeoutCallback
: () => void = () => {
220 /* This is intentional */
223 // Create a timeout promise that rejects in timeout milliseconds
224 const timeoutPromise
= new Promise
<never>((_
, reject
) => {
227 reject(timeoutError
);
231 // Returns a race between timeout promise and the passed promise
232 return Promise
.race
<T
>([promise
, timeoutPromise
]);
236 * Generate a cryptographically secure random number in the [0,1[ range
240 public static secureRandom(): number {
241 return crypto
.randomBytes(4).readUInt32LE() / 0x100000000;
244 public static JSONStringifyWithMapSupport(
245 obj
: Record
<string, unknown
> | Record
<string, unknown
>[],
248 return JSON
.stringify(
250 (key
, value
: Record
<string, unknown
>) => {
251 if (value
instanceof Map
) {
264 * Convert websocket error code to human readable string message
266 * @param code websocket error code
267 * @returns human readable string message
269 public static getWebSocketCloseEventStatusString(code
: number): string {
270 if (code
>= 0 && code
<= 999) {
272 } else if (code
>= 1016) {
274 return '(For WebSocket standard)';
275 } else if (code
<= 2999) {
276 return '(For WebSocket extensions)';
277 } else if (code
<= 3999) {
278 return '(For libraries and frameworks)';
279 } else if (code
<= 4999) {
280 return '(For applications)';
283 if (!Utils
.isUndefined(WebSocketCloseEventStatusString
[code
])) {
284 return WebSocketCloseEventStatusString
[code
] as string;