docs: enhance documentation and update changelog entries
[poolifier.git] / src / utils.ts
1 import { CircularArray } from './circular-array'
2 import type { WorkerChoiceStrategyOptions } from './pools/selection-strategies/selection-strategies-types'
3 import type { TasksUsage } from './pools/worker'
4
5 /**
6 * An intentional empty function.
7 */
8 export const EMPTY_FUNCTION: () => void = Object.freeze(() => {
9 /* Intentionally empty */
10 })
11
12 /**
13 * Initial tasks usage statistics.
14 */
15 export const INITIAL_TASKS_USAGE: TasksUsage = {
16 run: 0,
17 running: 0,
18 runTime: 0,
19 runTimeHistory: new CircularArray(),
20 avgRunTime: 0,
21 medRunTime: 0,
22 error: 0
23 }
24
25 /**
26 * Default worker choice strategy options.
27 */
28 export const DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS: WorkerChoiceStrategyOptions =
29 {
30 medRunTime: false
31 }
32
33 /**
34 * Compute the median of the given data set.
35 *
36 * @param dataSet - Data set.
37 * @returns The median of the given data set.
38 */
39 export const median = (dataSet: number[]): number => {
40 if (Array.isArray(dataSet) && dataSet.length === 1) {
41 return dataSet[0]
42 }
43 const sortedDataSet = dataSet.slice().sort((a, b) => a - b)
44 const middleIndex = Math.floor(sortedDataSet.length / 2)
45 if (sortedDataSet.length % 2 === 0) {
46 return sortedDataSet[middleIndex / 2]
47 }
48 return (sortedDataSet[middleIndex - 1] + sortedDataSet[middleIndex]) / 2
49 }