diff --git a/src/helpers.ts b/src/helpers.ts index 980dc0f..9b9c32e 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -243,11 +243,20 @@ export const sort = ( } } - const sorted = collection.slice().sort((a, b) => { + return collection.slice().sort((a, b) => { for (let i = 0, l = orders.length; i < l; i += 1) { const [keys, desc] = orders[i]; const aValue = getValue(a, keys); const bValue = getValue(b, keys); + + // Handle undefined values for sorting + const aUndef = typeof aValue === "undefined"; + const bUndef = typeof bValue === "undefined"; + // eslint-disable-next-line no-continue + if (aUndef && bUndef) continue; + if (aUndef) return desc ? 1 : -1; // undefined at bottom for descending, top for ascending + if (bUndef) return desc ? -1 : 1; + const r = comparator(aValue, bValue); if (r !== 0) return desc ? -r : r; } @@ -257,11 +266,6 @@ export const sort = ( const rid2 = getRid(b); return comparator(rid1, rid2); }); - - if (orders.length !== 1) return sorted; - - const [keys] = orders[0]; - return sorted.filter(d => typeof getValue(d, keys) !== "undefined"); }; export const paginate = ( diff --git a/test/misc.ts b/test/misc.ts index a28b3fd..fff7fdc 100644 --- a/test/misc.ts +++ b/test/misc.ts @@ -676,7 +676,11 @@ export const orderByWithEmptyNestedProperty = testQuery( query: "select * from c order by c.child.name", parameters: [{ name: "@name", value: "foo" }] }, - [{ id: "foo", child: { name: "foo" } }] + [ + { id: "bar", child: null }, + { id: "baz" }, + { id: "foo", child: { name: "foo" } } + ] ); export const deeplyNestedProperty = testQuery( @@ -797,12 +801,20 @@ export const multipleOrderByWithCompositeIndexes2 = testQuery( ] ); -export const filterUndefinedOrderBy = testQuery( +export const filterUndefinedOrderByASC = testQuery( + [{ id: "foo", sortKey: "a" }, { id: "bar" }, { id: "baz", sortKey: "b" }], + { + query: "SELECT * FROM c ORDER BY c.sortKey ASC" + }, + [{ id: "bar" }, { id: "foo", sortKey: "a" }, { id: "baz", sortKey: "b" }] +); + +export const filterUndefinedOrderByDESC = testQuery( [{ id: "foo", sortKey: "a" }, { id: "bar" }, { id: "baz", sortKey: "b" }], { - query: "SELECT * FROM c ORDER BY c.sortKey" + query: "SELECT * FROM c ORDER BY c.sortKey DESC" }, - [{ id: "foo", sortKey: "a" }, { id: "baz", sortKey: "b" }] + [{ id: "baz", sortKey: "b" }, { id: "foo", sortKey: "a" }, { id: "bar" }] ); export const DoNotfilterUndefinedMultipleOrderBy = testQuery(