diff --git a/src/core/lib/Arithmetic.mjs b/src/core/lib/Arithmetic.mjs index 7c10855fa..5fbc5771b 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 fb03a5f71..702d552ef 100644 --- a/tests/operations/index.mjs +++ b/tests/operations/index.mjs @@ -109,6 +109,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 000000000..555f2edd2 --- /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"], + }, + ], + }, +]);