X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils.ts;h=d85c5ba58b4988fad867a9b35f9dca5bb5bb2b45;hb=765457872257684691f93befb94175a2aaa83502;hp=753219c5e37d367b8d5d83790f76847445d36663;hpb=4f3c3d894171421375559b43ce469bd5ccb475da;p=poolifier.git diff --git a/src/utils.ts b/src/utils.ts index 753219c5..d85c5ba5 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -6,6 +6,19 @@ export const EMPTY_FUNCTION: () => void = Object.freeze(() => { }) /** - * An intentional empty object literal. + * Returns the median of the given data set. + * + * @param dataSet - Data set. + * @returns The median of the given data set. */ -export const EMPTY_OBJECT_LITERAL = {} +export const median = (dataSet: number[]): number => { + if (Array.isArray(dataSet) && dataSet.length === 1) { + return dataSet[0] + } + const sortedDataSet = dataSet.slice().sort((a, b) => a - b) + const middleIndex = Math.floor(sortedDataSet.length / 2) + if (sortedDataSet.length % 2 === 0) { + return sortedDataSet[middleIndex / 2] + } + return (sortedDataSet[middleIndex - 1] + sortedDataSet[middleIndex]) / 2 +}