diff --git a/src/groupSort.js b/src/groupSort.js index 2d56ccf..63aba28 100644 --- a/src/groupSort.js +++ b/src/groupSort.js @@ -1,10 +1,9 @@ -import ascending from "./ascending.js"; import group, {rollup} from "./group.js"; -import sort from "./sort.js"; +import sort, {ascendingDefined} from "./sort.js"; export default function groupSort(values, reduce, key) { return (reduce.length !== 2 - ? sort(rollup(values, reduce, key), (([ak, av], [bk, bv]) => ascending(av, bv) || ascending(ak, bk))) - : sort(group(values, key), (([ak, av], [bk, bv]) => reduce(av, bv) || ascending(ak, bk)))) + ? sort(rollup(values, reduce, key), (([ak, av], [bk, bv]) => ascendingDefined(av, bv) || ascendingDefined(ak, bk))) + : sort(group(values, key), (([ak, av], [bk, bv]) => reduce(av, bv) || ascendingDefined(ak, bk)))) .map(([key]) => key); } diff --git a/test/groupSort-test.js b/test/groupSort-test.js index 2d7d76b..6260d4f 100644 --- a/test/groupSort-test.js +++ b/test/groupSort-test.js @@ -31,6 +31,11 @@ it("groupSort(data, reduce, key) returns sorted keys when reduce is an accessor" ); }); +it("groupSort(data, reduce, key) puts non-orderable reduced values last", () => { + const data = [{key: "z", value: 2}, {key: "a", value: null}, {key: "m", value: 1}]; + assert.deepStrictEqual(groupSort(data, g => g[0].value, d => d.key), ["m", "z", "a"]); +}); + it("groupSort(data, reduce, key) returns sorted keys when reduce is a comparator", () => { assert.deepStrictEqual( groupSort(barley, (a, b) => ascending(median(a, d => d.yield), median(b, d => d.yield)), d => d.variety),