chore: switch coding style to JS standard
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerUtils.ts
1 import { getRandomValues } from 'node:crypto'
2
3 import chalk from 'chalk'
4
5 export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => {
6 return await new Promise<NodeJS.Timeout>((resolve) =>
7 setTimeout(resolve as () => void, milliSeconds)
8 )
9 }
10
11 export const defaultExitHandler = (code: number): void => {
12 if (code === 0) {
13 console.info(chalk.green('Worker exited successfully'))
14 } else if (code === 1) {
15 console.info(chalk.green('Worker terminated successfully'))
16 } else if (code > 1) {
17 console.error(chalk.red(`Worker exited with exit code: ${code.toString()}`))
18 }
19 }
20
21 export const defaultErrorHandler = (error: Error): void => {
22 console.error(chalk.red('Worker errored: '), error)
23 }
24
25 export const randomizeDelay = (delay: number): number => {
26 const random = secureRandom()
27 const sign = random < 0.5 ? -1 : 1
28 const randomSum = delay * 0.2 * random // 0-20% of the delay
29 return delay + sign * randomSum
30 }
31
32 /**
33 * Generates a cryptographically secure random number in the [0,1[ range
34 *
35 * @returns A number in the [0,1[ range
36 * @internal
37 */
38 const secureRandom = (): number => {
39 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
40 }