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