Skip to content

Commit b0b374f

Browse files
committed
feat: allow sorting by comparator function
1 parent e9a30f6 commit b0b374f

File tree

1 file changed

+23
-13
lines changed

1 file changed

+23
-13
lines changed

src/lib/transforms/sort.ts

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -22,21 +22,31 @@ export function sort(
2222
sort.channel = sort.channel.substring(1);
2323
sort.order = 'descending';
2424
}
25+
// if sort is a function that does not take exactly one argument, we treat it
26+
// as comparator function, as you would pass to array.sort
27+
const isComparator = typeof channels.sort === 'function' && channels.sort.length !== 1;
28+
2529
// sort data
2630
return {
27-
data: data
28-
.map((d) => ({
29-
...d,
30-
[SORT_KEY]: resolveChannel('sort', d, { ...channels, sort })
31-
}))
32-
.toSorted(
33-
(a, b) =>
34-
(a[SORT_KEY] > b[SORT_KEY] ? 1 : a[SORT_KEY] < b[SORT_KEY] ? -1 : 0) *
35-
(options.reverse || (isDataRecord(sort) && sort?.order === 'descending')
36-
? -1
37-
: 1)
38-
)
39-
.map(({ [SORT_KEY]: a, ...rest }) => rest),
31+
data: isComparator
32+
? data.toSorted(channels.sort as (a: DataRecord, b: DataRecord) => number)
33+
: data
34+
.map((d) => ({
35+
...d,
36+
[SORT_KEY]: resolveChannel('sort', d, { ...channels, sort }) as
37+
| number
38+
| Date
39+
| string
40+
}))
41+
.toSorted(
42+
(a, b) =>
43+
(a[SORT_KEY] > b[SORT_KEY] ? 1 : a[SORT_KEY] < b[SORT_KEY] ? -1 : 0) *
44+
(options.reverse ||
45+
(isDataRecord(sort) && sort?.order === 'descending')
46+
? -1
47+
: 1)
48+
)
49+
.map(({ [SORT_KEY]: a, ...rest }) => rest),
4050

4151
...channels,
4252
[IS_SORTED]: sort,

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy