Fix median sorting regression
Co-authored-by: williballenthin <156560+williballenthin@users.noreply.github.com>
This commit is contained in:
parent
4fc39bc024
commit
b16f9ec134
@ -108,14 +108,17 @@ export function mean(data) {
|
|||||||
* @returns {BigNumber}
|
* @returns {BigNumber}
|
||||||
*/
|
*/
|
||||||
export function median(data) {
|
export function median(data) {
|
||||||
if ((data.length % 2) === 0 && data.length > 0) {
|
if (data.length > 0) {
|
||||||
data.sort(function(a, b) {
|
data.sort(function(a, b) {
|
||||||
return a.minus(b);
|
return a.minus(b);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if ((data.length % 2) === 0) {
|
||||||
const first = data[Math.floor(data.length / 2)];
|
const first = data[Math.floor(data.length / 2)];
|
||||||
const second = data[Math.floor(data.length / 2) - 1];
|
const second = data[Math.floor(data.length / 2) - 1];
|
||||||
return mean([first, second]);
|
return mean([first, second]);
|
||||||
} else {
|
}
|
||||||
|
|
||||||
return data[Math.floor(data.length / 2)];
|
return data[Math.floor(data.length / 2)];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -22,6 +22,7 @@ import "./tests/File.mjs";
|
|||||||
import "./tests/Dish.mjs";
|
import "./tests/Dish.mjs";
|
||||||
import "./tests/NodeDish.mjs";
|
import "./tests/NodeDish.mjs";
|
||||||
import "./tests/Utils.mjs";
|
import "./tests/Utils.mjs";
|
||||||
|
import "./tests/Arithmetic.mjs";
|
||||||
import "./tests/Categories.mjs";
|
import "./tests/Categories.mjs";
|
||||||
import "./tests/lib/BigIntUtils.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…
x
Reference in New Issue
Block a user