Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions src/core/lib/Arithmetic.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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)];
}
}
Expand Down
1 change: 1 addition & 0 deletions tests/operations/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
33 changes: 33 additions & 0 deletions tests/operations/tests/Median.mjs
Original file line number Diff line number Diff line change
@@ -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"],
},
],
},
]);