Skip to content

Commit c642ef8

Browse files
committed
refactor: simplify how groups are clustered
1 parent c678223 commit c642ef8

File tree

1 file changed

+14
-19
lines changed

1 file changed

+14
-19
lines changed

site/src/api/queries/groups.ts

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,21 @@ export function groupsByUserId(organizationId: string) {
3131
return {
3232
...groups(organizationId),
3333
select: (allGroups) => {
34-
const userIdMapper = new Map<string, Group[]>();
34+
// Sorting here means that nothing has to be sorted for the individual
35+
// user arrays later
36+
const sorted = [...allGroups].sort((g1, g2) => {
37+
const key =
38+
g1.display_name && g2.display_name ? "display_name" : "name";
3539

36-
for (const group of allGroups) {
40+
if (g1[key] === g2[key]) {
41+
return 0;
42+
}
43+
44+
return g1[key] < g2[key] ? -1 : 1;
45+
});
46+
47+
const userIdMapper = new Map<string, Group[]>();
48+
for (const group of sorted) {
3749
for (const user of group.members) {
3850
let groupsForUser = userIdMapper.get(user.id);
3951
if (groupsForUser === undefined) {
@@ -45,23 +57,6 @@ export function groupsByUserId(organizationId: string) {
4557
}
4658
}
4759

48-
// Defined outside the loop because it can be reused by all group arrays,
49-
// and doesn't need to be rebuilt from scratch on each iteration
50-
const orderGroupsByName = (g1: Group, g2: Group) => {
51-
const key =
52-
g1.display_name && g2.display_name ? "display_name" : "name";
53-
54-
if (g1[key] === g2[key]) {
55-
return 0;
56-
}
57-
58-
return g1[key] < g2[key] ? -1 : 1;
59-
};
60-
61-
for (const groupsList of userIdMapper.values()) {
62-
groupsList.sort(orderGroupsByName);
63-
}
64-
6560
return userIdMapper as GroupsByUserId;
6661
},
6762
} satisfies UseQueryOptions<Group[], unknown, GroupsByUserId>;

0 commit comments

Comments
 (0)