From ea86cd59c81b78f2ffe153b7882b5834d36a5db3 Mon Sep 17 00:00:00 2001 From: Willi Ballenthin Date: Tue, 24 Mar 2026 09:11:35 +0100 Subject: [PATCH] fix Median operation returns incorrect result for unsorted odd-length inputs closes #2239 --- src/core/lib/Arithmetic.mjs | 13 +++++++----- tests/operations/index.mjs | 1 + tests/operations/tests/Median.mjs | 33 +++++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 5 deletions(-) create mode 100644 tests/operations/tests/Median.mjs diff --git a/src/core/lib/Arithmetic.mjs b/src/core/lib/Arithmetic.mjs index 7c10855f..5fbc5771 100644 --- a/src/core/lib/Arithmetic.mjs +++ b/src/core/lib/Arithmetic.mjs @@ -108,14 +108,17 @@ export function mean(data) { * @returns {BigNumber} */ export function median(data) { - if ((data.length % 2) === 0 && data.length > 0) { + if (data.length > 0) { data.sort(function(a, b) { return a.minus(b); }); - const first = data[Math.floor(data.length / 2)]; - const second = data[Math.floor(data.length / 2) - 1]; - return mean([first, second]); - } else { + + if ((data.length % 2) === 0) { + const first = data[Math.floor(data.length / 2)]; + const second = data[Math.floor(data.length / 2) - 1]; + return mean([first, second]); + } + return data[Math.floor(data.length / 2)]; } } diff --git a/tests/operations/index.mjs b/tests/operations/index.mjs index f030349d..98631405 100644 --- a/tests/operations/index.mjs +++ b/tests/operations/index.mjs @@ -111,6 +111,7 @@ import "./tests/LuhnChecksum.mjs"; import "./tests/LZNT1Decompress.mjs"; import "./tests/LZString.mjs"; import "./tests/Magic.mjs"; +import "./tests/Median.mjs"; import "./tests/Media.mjs"; import "./tests/MIMEDecoding.mjs"; import "./tests/Modhex.mjs"; diff --git a/tests/operations/tests/Median.mjs b/tests/operations/tests/Median.mjs new file mode 100644 index 00000000..555f2edd --- /dev/null +++ b/tests/operations/tests/Median.mjs @@ -0,0 +1,33 @@ +/** + * Median operation tests. + * + * @author copilot-swe-agent[bot] + * @copyright Crown Copyright 2018 + * @license Apache-2.0 + */ +import TestRegister from "../../lib/TestRegister.mjs"; + +TestRegister.addTests([ + { + name: "Median: odd-length input", + input: "10 1 2", + expectedOutput: "2", + recipeConfig: [ + { + op: "Median", + args: ["Space"], + }, + ], + }, + { + name: "Median: even-length input", + input: "10 1 2 5", + expectedOutput: "3.5", + recipeConfig: [ + { + op: "Median", + args: ["Space"], + }, + ], + }, +]);