From d27d073362e19e88ed9aa17696b9d39b84780cb1 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Mon, 8 May 2023 22:50:17 +0200 Subject: [PATCH] refactor: remove unneeded array building in median computation MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/utils.ts | 2 +- tests/utils.test.js | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index e56c058e..c6e78ab5 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -25,7 +25,7 @@ export const median = (dataSet: number[]): number => { if (Array.isArray(dataSet) && dataSet.length === 1) { return dataSet[0] } - dataSet = [...dataSet].slice().sort((a, b) => a - b) + dataSet = dataSet.slice().sort((a, b) => a - b) return (dataSet[(dataSet.length - 1) >> 1] + dataSet[dataSet.length >> 1]) / 2 } diff --git a/tests/utils.test.js b/tests/utils.test.js index c08efbc1..eb0e7b15 100644 --- a/tests/utils.test.js +++ b/tests/utils.test.js @@ -3,8 +3,10 @@ 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(3.05) + const array0 = [0.08] + expect(median(array0)).toBe(0.08) + const array1 = [0.25, 4.75, 3.05, 6.04, 1.01, 2.02, 5.03] + expect(median(array1)).toBe(3.05) }) it('Verify isPlainObject() behavior', () => { -- 2.34.1