Skip to content

Commit

Permalink
Merge pull request #3317 from tloncorp/po/perf-speed-up-sidebar-sort
Browse files Browse the repository at this point in the history
perf: speed up sidebar sorter
  • Loading branch information
patosullivan authored Mar 7, 2024
2 parents 254a881 + ec64891 commit 12bab6e
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions apps/tlon-web/src/logic/useSidebarSort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,17 +106,24 @@ export default function useSidebarSort({
records: Record<string, T>,
accessor: (k: string, v: T) => string,
reverse = false
) => {
const entries = Object.entries(records);
entries.sort(([aKey, aObj], [bKey, bObj]) => {
const aVal = accessor(aKey, aObj);
const bVal = accessor(bKey, bObj);
): [string, T][] => {
// pre-compute values for comparison
const entries = Object.entries(records).map(([key, obj]) => ({
key,
obj,
value: accessor(key, obj),
}));

// integrate reverse sorting logic into the comparison
const directionMultiplier = reverse ? -1 : 1;

entries.sort((a, b) => {
const sorter = sortOptions[sortFn] ?? sortOptions[RECENT_SORT];
return sorter(aVal, bVal);
return directionMultiplier * sorter(a.value, b.value);
});

return reverse ? entries.reverse() : entries;
// map back to the original format
return entries.map(({ key, obj }) => [key, obj]);
},
[sortFn, sortOptions]
);
Expand Down

0 comments on commit 12bab6e

Please sign in to comment.