mirror of
https://github.com/gchq/CyberChef.git
synced 2026-03-18 04:41:40 -07:00
Fix median sorting regression
Co-authored-by: williballenthin <156560+williballenthin@users.noreply.github.com>
This commit is contained in:
parent
4fc39bc024
commit
b16f9ec134
3 changed files with 26 additions and 5 deletions
|
|
@ -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)];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ import "./tests/File.mjs";
|
|||
import "./tests/Dish.mjs";
|
||||
import "./tests/NodeDish.mjs";
|
||||
import "./tests/Utils.mjs";
|
||||
import "./tests/Arithmetic.mjs";
|
||||
import "./tests/Categories.mjs";
|
||||
import "./tests/lib/BigIntUtils.mjs";
|
||||
|
||||
|
|
|
|||
17
tests/node/tests/Arithmetic.mjs
Normal file
17
tests/node/tests/Arithmetic.mjs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import assert from "assert";
|
||||
import BigNumber from "bignumber.js";
|
||||
import it from "../assertionHandler.mjs";
|
||||
import TestRegister from "../../lib/TestRegister.mjs";
|
||||
import { median } from "../../../src/core/lib/Arithmetic.mjs";
|
||||
|
||||
TestRegister.addApiTests([
|
||||
it("Arithmetic: median sorts odd-length input", () => {
|
||||
const result = median([new BigNumber(10), new BigNumber(1), new BigNumber(2)]);
|
||||
assert.strictEqual(result.toString(), "2");
|
||||
}),
|
||||
|
||||
it("Arithmetic: median keeps even-length behavior", () => {
|
||||
const result = median([new BigNumber(10), new BigNumber(1), new BigNumber(2), new BigNumber(5)]);
|
||||
assert.strictEqual(result.toString(), "3.5");
|
||||
}),
|
||||
]);
|
||||
Loading…
Add table
Add a link
Reference in a new issue