1 import crypto from
'crypto';
3 import { WebSocketCloseEventStatusString
} from
'../types/WebSocket';
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 {
15 return crypto
.randomUUID();
18 public static validateUUID(uuid
: string): boolean {
19 return /^[0-9a
-fA
-F
]{8}-[0-9a
-fA
-F
]{4}-4[0-9a
-fA
-F
]{3}-[0-9a
-fA
-F
]{4}-[0-9a
-fA
-F
]{12}$
/.test(
24 public static async sleep(milliSeconds
: number): Promise
<NodeJS
.Timeout
> {
25 return new Promise((resolve
) => setTimeout(resolve
as () => void, milliSeconds
));
28 public static formatDurationMilliSeconds(duration
: number): string {
29 duration
= Utils
.convertToInt(duration
);
30 const hours
= Math.floor(duration
/ (3600 * 1000));
31 const minutes
= Math.floor((duration
/ 1000 - hours
* 3600) / 60);
32 const seconds
= duration
/ 1000 - hours
* 3600 - minutes
* 60;
33 let hoursStr
= hours
.toString();
34 let minutesStr
= minutes
.toString();
35 let secondsStr
= seconds
.toString();
38 hoursStr
= '0' + hours
.toString();
41 minutesStr
= '0' + minutes
.toString();
44 secondsStr
= '0' + seconds
.toString();
46 return hoursStr
+ ':' + minutesStr
+ ':' + secondsStr
.substring(0, 6);
49 public static formatDurationSeconds(duration
: number): string {
50 return Utils
.formatDurationMilliSeconds(duration
* 1000);
53 public static convertToDate(value
: unknown
): Date {
59 if (!(value
instanceof Date)) {
60 return new Date(value
as string);
65 public static convertToInt(value
: unknown
): number {
66 let changedValue
: number = value
as number;
70 if (Number.isSafeInteger(value
)) {
71 return value
as number;
73 if (typeof value
=== 'number') {
74 changedValue
= Math.trunc(value
);
76 if (Utils
.isString(value
)) {
77 changedValue
= parseInt(value
as string);
82 public static convertToFloat(value
: unknown
): number {
83 let changedValue
: number = value
as number;
87 if (Utils
.isString(value
)) {
88 changedValue
= parseFloat(value
as string);
93 public static convertToBoolean(value
: unknown
): boolean {
97 if (typeof value
=== 'boolean') {
100 Utils
.isString(value
) &&
101 ((value
as string).toLowerCase() === 'true' || value
=== '1')
104 } else if (typeof value
=== 'number' && value
=== 1) {
111 public static getRandomFloat(max
= Number.MAX_VALUE
, min
= 0, negative
= false): number {
112 if (max
< min
|| max
< 0 || min
< 0) {
113 throw new RangeError('Invalid interval');
115 const randomPositiveFloat
= crypto
.randomBytes(4).readUInt32LE() / 0xffffffff;
116 const sign
= negative
&& randomPositiveFloat
< 0.5 ? -1 : 1;
117 return sign
* (randomPositiveFloat
* (max
- min
) + min
);
120 public static getRandomInteger(max
= Number.MAX_SAFE_INTEGER
, min
= 0): number {
121 if (max
< min
|| max
< 0 || min
< 0) {
122 throw new RangeError('Invalid interval');
124 max
= Math.floor(max
);
125 if (!Utils
.isNullOrUndefined(min
) && min
!== 0) {
126 min
= Math.ceil(min
);
127 return Math.floor(Utils
.secureRandom() * (max
- min
+ 1)) + min
;
129 return Math.floor(Utils
.secureRandom() * (max
+ 1));
132 public static roundTo(numberValue
: number, scale
: number): number {
133 const roundPower
= Math.pow(10, scale
);
134 return Math.round(numberValue
* roundPower
) / roundPower
;
137 public static truncTo(numberValue
: number, scale
: number): number {
138 const truncPower
= Math.pow(10, scale
);
139 return Math.trunc(numberValue
* truncPower
) / truncPower
;
142 public static getRandomFloatRounded(max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number {
144 return Utils
.roundTo(Utils
.getRandomFloat(max
, min
), scale
);
146 return Utils
.roundTo(Utils
.getRandomFloat(max
), scale
);
149 public static getRandomFloatFluctuatedRounded(
151 fluctuationPercent
: number,
154 if (fluctuationPercent
=== 0) {
155 return Utils
.roundTo(staticValue
, scale
);
157 const fluctuationRatio
= fluctuationPercent
/ 100;
158 return Utils
.getRandomFloatRounded(
159 staticValue
* (1 + fluctuationRatio
),
160 staticValue
* (1 - fluctuationRatio
),
165 public static cloneObject
<T
>(object
: T
): T
{
166 return JSON
.parse(JSON
.stringify(object
)) as T
;
169 public static isIterable
<T
>(obj
: T
): boolean {
170 return obj
? typeof obj
[Symbol
.iterator
] === 'function' : false;
173 public static isString(value
: unknown
): boolean {
174 return typeof value
=== 'string';
177 public static isEmptyString(value
: unknown
): boolean {
178 return Utils
.isString(value
) && (value
as string).trim().length
=== 0;
181 public static isUndefined(value
: unknown
): boolean {
182 return typeof value
=== 'undefined';
185 public static isNullOrUndefined(value
: unknown
): boolean {
186 // eslint-disable-next-line eqeqeq, no-eq-null
187 return value
== null ? true : false;
190 public static isEmptyArray(object
: unknown
| unknown
[]): boolean {
191 if (!Array.isArray(object
)) {
194 if (object
.length
> 0) {
200 public static isEmptyObject(obj
: object
): boolean {
201 if (obj
?.constructor
!== Object) {
204 // Iterates over the keys of an object, if
205 // any exist, return false.
206 for (const _
in obj
) {
212 public static insertAt
= (str
: string, subStr
: string, pos
: number): string =>
213 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
216 * @param [retryNumber=0]
217 * @returns delay in milliseconds
219 public static exponentialDelay(retryNumber
= 0): number {
220 const delay
= Math.pow(2, retryNumber
) * 100;
221 const randomSum
= delay
* 0.2 * Utils
.secureRandom(); // 0-20% of the delay
222 return delay
+ randomSum
;
225 public static async promiseWithTimeout
<T
>(
229 timeoutCallback
: () => void = () => {
230 /* This is intentional */
233 // Create a timeout promise that rejects in timeout milliseconds
234 const timeoutPromise
= new Promise
<never>((_
, reject
) => {
237 reject(timeoutError
);
241 // Returns a race between timeout promise and the passed promise
242 return Promise
.race
<T
>([promise
, timeoutPromise
]);
246 * Generate a cryptographically secure random number in the [0,1[ range
250 public static secureRandom(): number {
251 return crypto
.randomBytes(4).readUInt32LE() / 0x100000000;
254 public static JSONStringifyWithMapSupport(
255 obj
: Record
<string, unknown
> | Record
<string, unknown
>[],
258 return JSON
.stringify(
260 (key
, value
: Record
<string, unknown
>) => {
261 if (value
instanceof Map
) {
274 * Convert websocket error code to human readable string message
276 * @param code websocket error code
277 * @returns human readable string message
279 public static getWebSocketCloseEventStatusString(code
: number): string {
280 if (code
>= 0 && code
<= 999) {
282 } else if (code
>= 1016) {
284 return '(For WebSocket standard)';
285 } else if (code
<= 2999) {
286 return '(For WebSocket extensions)';
287 } else if (code
<= 3999) {
288 return '(For libraries and frameworks)';
289 } else if (code
<= 4999) {
290 return '(For applications)';
293 if (!Utils
.isUndefined(WebSocketCloseEventStatusString
[code
])) {
294 return WebSocketCloseEventStatusString
[code
] as string;