perf: optimize median computation implementation
[poolifier.git] / src / utils.ts
1 import type { WorkerChoiceStrategyOptions } from './pools/selection-strategies/selection-strategies-types'
2
3 /**
4 * An intentional empty function.
5 */
6 export const EMPTY_FUNCTION: () => void = Object.freeze(() => {
7 /* Intentionally empty */
8 })
9
10 /**
11 * Default worker choice strategy options.
12 */
13 export const DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS: WorkerChoiceStrategyOptions =
14 {
15 medRunTime: false
16 }
17
18 /**
19 * Compute the median of the given data set.
20 *
21 * @param dataSet - Data set.
22 * @returns The median of the given data set.
23 */
24 export const median = (dataSet: number[]): number => {
25 if (Array.isArray(dataSet) && dataSet.length === 0) {
26 return 0
27 }
28 if (Array.isArray(dataSet) && dataSet.length === 1) {
29 return dataSet[0]
30 }
31 const sortedDataSet = dataSet.slice().sort((a, b) => a - b)
32 if (sortedDataSet.length % 2 === 0) {
33 return sortedDataSet[sortedDataSet.length / 2]
34 }
35 return (
36 (sortedDataSet[(sortedDataSet.length - 1) >> 1] +
37 sortedDataSet[sortedDataSet.length >> 1]) /
38 2
39 )
40 }
41
42 export const isPlainObject = (obj: unknown): boolean =>
43 typeof obj === 'object' &&
44 obj !== null &&
45 obj?.constructor === Object &&
46 Object.prototype.toString.call(obj) === '[object Object]'