From: Jérôme Benoit Date: Mon, 8 May 2023 20:45:36 +0000 (+0200) Subject: fix: fix median computation X-Git-Tag: v2.4.14~12 X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=cdef2f76a5cf8fc6f90f94d4e36de8fcbe0c5c9d;p=poolifier.git fix: fix median computation Signed-off-by: Jérôme Benoit --- diff --git a/src/utils.ts b/src/utils.ts index ed118da6..e56c058e 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -25,12 +25,8 @@ 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] - } - return (sortedDataSet[middleIndex - 1] + sortedDataSet[middleIndex]) / 2 + dataSet = [...dataSet].slice().sort((a, b) => a - b) + return (dataSet[(dataSet.length - 1) >> 1] + dataSet[dataSet.length >> 1]) / 2 } export const isPlainObject = (obj: unknown): boolean => diff --git a/tests/utils.test.js b/tests/utils.test.js index 7d4040ce..c08efbc1 100644 --- a/tests/utils.test.js +++ b/tests/utils.test.js @@ -4,7 +4,7 @@ const { isPlainObject, median } = require('../lib/utils') describe('Utils test suite', () => { it('Verify median computation', () => { const array = [0.25, 4.75, 3.05, 6.04, 1.01, 2.02, 5.03] - expect(median(array)).toBe(2.535) + expect(median(array)).toBe(3.05) }) it('Verify isPlainObject() behavior', () => {