refactor: untangle utils purpose
[poolifier.git] / src / utils.ts
CommitLineData
aa4bf4b2 1import * as os from 'node:os'
e9ed6eee 2import { getRandomValues } from 'node:crypto'
d35e5717 3import type { KillBehavior } from './worker/worker-options.js'
bbeadd16 4
ff128cc9
JB
5/**
6 * Default task name.
7 */
8export const DEFAULT_TASK_NAME = 'default'
9
6e9d10db
JB
10/**
11 * An intentional empty function.
12 */
4f3c3d89 13export const EMPTY_FUNCTION: () => void = Object.freeze(() => {
6e9d10db 14 /* Intentionally empty */
4f3c3d89 15})
78099a15 16
51474716 17/**
ab80dc46
JB
18 * Returns safe host OS optimized estimate of the default amount of parallelism a pool should use.
19 * Always returns a value greater than zero.
20 *
21 * @returns The host OS optimized maximum pool size.
51474716
JB
22 */
23export const availableParallelism = (): number => {
24 let availableParallelism = 1
25 try {
aa4bf4b2 26 availableParallelism = os.availableParallelism()
51474716 27 } catch {
562a4037
JB
28 const cpus = os.cpus()
29 if (Array.isArray(cpus) && cpus.length > 0) {
30 availableParallelism = cpus.length
51474716
JB
31 }
32 }
33 return availableParallelism
34}
35
68cbdc84
JB
36/**
37 * Sleeps for the given amount of milliseconds.
38 *
39 * @param ms - The amount of milliseconds to sleep.
40 * @returns A promise that resolves after the given amount of milliseconds.
57a29f75 41 * @internal
68cbdc84
JB
42 */
43export const sleep = async (ms: number): Promise<void> => {
041dc05b 44 await new Promise(resolve => {
68cbdc84
JB
45 setTimeout(resolve, ms)
46 })
47}
48
49/**
50 * Computes the retry delay in milliseconds using an exponential back off algorithm.
51 *
52 * @param retryNumber - The number of retries that have already been attempted
147be6fe 53 * @param delayFactor - The base delay factor in milliseconds
68cbdc84
JB
54 * @returns Delay in milliseconds
55 * @internal
56 */
57export const exponentialDelay = (
58 retryNumber = 0,
147be6fe 59 delayFactor = 100
68cbdc84 60): number => {
147be6fe
JB
61 const delay = Math.pow(2, retryNumber) * delayFactor
62 const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay
68cbdc84
JB
63 return delay + randomSum
64}
8990357d 65
dc021bcc
JB
66/**
67 * Computes the average of the given data set.
68 *
69 * @param dataSet - Data set.
70 * @returns The average of the given data set.
71 * @internal
72 */
73export const average = (dataSet: number[]): number => {
74 if (Array.isArray(dataSet) && dataSet.length === 0) {
75 return 0
e9ed6eee 76 } else if (Array.isArray(dataSet) && dataSet.length === 1) {
dc021bcc
JB
77 return dataSet[0]
78 }
79 return (
80 dataSet.reduce((accumulator, number) => accumulator + number, 0) /
81 dataSet.length
82 )
83}
84
bbeadd16 85/**
afe0d5bf 86 * Computes the median of the given data set.
78099a15
JB
87 *
88 * @param dataSet - Data set.
89 * @returns The median of the given data set.
4bffc062 90 * @internal
78099a15
JB
91 */
92export const median = (dataSet: number[]): number => {
4a45e8d2
JB
93 if (Array.isArray(dataSet) && dataSet.length === 0) {
94 return 0
e9ed6eee 95 } else if (Array.isArray(dataSet) && dataSet.length === 1) {
78099a15
JB
96 return dataSet[0]
97 }
c6f42dd6
JB
98 const sortedDataSet = dataSet.slice().sort((a, b) => a - b)
99 return (
100 (sortedDataSet[(sortedDataSet.length - 1) >> 1] +
101 sortedDataSet[sortedDataSet.length >> 1]) /
102 2
103 )
78099a15 104}
0d80593b 105
afe0d5bf
JB
106/**
107 * Rounds the given number to the given scale.
64383951 108 * The rounding is done using the "round half away from zero" method.
afe0d5bf
JB
109 *
110 * @param num - The number to round.
111 * @param scale - The scale to round to.
112 * @returns The rounded number.
57a29f75 113 * @internal
afe0d5bf
JB
114 */
115export const round = (num: number, scale = 2): number => {
116 const rounder = Math.pow(10, scale)
117 return Math.round(num * rounder * (1 + Number.EPSILON)) / rounder
118}
119
3c653a03
JB
120/**
121 * Is the given object a plain object?
122 *
123 * @param obj - The object to check.
124 * @returns `true` if the given object is a plain object, `false` otherwise.
57a29f75 125 * @internal
3c653a03 126 */
e9ed6eee 127export const isPlainObject = (obj: unknown): obj is object =>
0d80593b
JB
128 typeof obj === 'object' &&
129 obj !== null &&
c63a35a0 130 obj.constructor === Object &&
0d80593b 131 Object.prototype.toString.call(obj) === '[object Object]'
59317253
JB
132
133/**
134 * Detects whether the given value is a kill behavior or not.
135 *
136 * @typeParam KB - Which specific KillBehavior type to test against.
137 * @param killBehavior - Which kind of kill behavior to detect.
138 * @param value - Any value.
139 * @returns `true` if `value` was strictly equals to `killBehavior`, otherwise `false`.
4bffc062 140 * @internal
59317253
JB
141 */
142export const isKillBehavior = <KB extends KillBehavior>(
143 killBehavior: KB,
144 value: unknown
145): value is KB => {
146 return value === killBehavior
147}
49d1b48c
JB
148
149/**
150 * Detects whether the given value is an asynchronous function or not.
151 *
e9ed6eee 152 * @param fn - Unknown value.
49d1b48c 153 * @returns `true` if `fn` was an asynchronous function, otherwise `false`.
57a29f75 154 * @internal
49d1b48c
JB
155 */
156export const isAsyncFunction = (
157 fn: unknown
158): fn is (...args: unknown[]) => Promise<unknown> => {
159 return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction'
160}
e4f20deb 161
68cbdc84 162/**
57a29f75 163 * Generates a cryptographically secure random number in the [0,1[ range
68cbdc84
JB
164 *
165 * @returns A number in the [0,1[ range
57a29f75 166 * @internal
68cbdc84 167 */
970b38d6 168export const secureRandom = (): number => {
304d379e 169 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
68cbdc84 170}
68e7ed58 171
57a29f75
JB
172/**
173 * Returns the minimum of the given numbers.
174 * If no numbers are given, `Infinity` is returned.
175 *
176 * @param args - The numbers to get the minimum of.
177 * @returns The minimum of the given numbers.
178 * @internal
179 */
90d6701c
JB
180export const min = (...args: number[]): number =>
181 args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity)
182
57a29f75
JB
183/**
184 * Returns the maximum of the given numbers.
185 * If no numbers are given, `-Infinity` is returned.
186 *
187 * @param args - The numbers to get the maximum of.
188 * @returns The maximum of the given numbers.
189 * @internal
190 */
90d6701c
JB
191export const max = (...args: number[]): number =>
192 args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity)
d91689fd
JB
193
194/**
195 * Wraps a function so that it can only be called once.
196 *
197 * @param fn - The function to wrap.
198 * @param context - The context to bind the function to.
199 * @returns The wrapped function.
200 * @internal
201 */
202// eslint-disable-next-line @typescript-eslint/no-explicit-any
203export const once = <T, A extends any[], R>(
204 fn: (...args: A) => R,
205 context: T
206): ((...args: A) => R) => {
207 let result: R
208 return (...args: A) => {
c63a35a0 209 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
d91689fd
JB
210 if (fn != null) {
211 result = fn.apply<T, A, R>(context, args)
212 ;(fn as unknown as undefined) = (context as unknown as undefined) =
213 undefined
214 }
215 return result
216 }
217}