This commit is contained in:
Willi Ballenthin 2026-03-15 19:11:28 +01:00 committed by GitHub
commit 5eb3e02e8d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 42 additions and 5 deletions

View file

@ -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)];
}
}

View file

@ -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";

View file

@ -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"],
},
],
},
]);