Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@

## 2024-03-10 - O(N²) array searches to O(1) Hash Maps lookup
**Learning:** In judging benchmarks and results array loops, we mapped over elements and used `.filter()`, `.findIndex()` or `.some()` which resulted in inefficient O(N²) complexity.
**Action:** When working on React components or trpc array calculations, avoid expensive nested iterations. Move derived array calculations to use pre-computed `Map` (hash maps), and take advantage of `Map.groupBy` to transform elements into O(1) loop-ups.
79 changes: 45 additions & 34 deletions src/server/api/routers/judging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,9 +349,7 @@ const synchronizeProjectRecusal = async (
assignment.recusedAt === null &&
assignment.assignmentReason?.startsWith("automatic recusal replacement for "),
)
.map(assignment =>
assignment.assignmentReason?.slice("automatic recusal replacement for ".length),
)
.map(assignment => assignment.assignmentReason?.slice("automatic recusal replacement for ".length))
.filter((id): id is string => Boolean(id)),
);
const missingCoverageIds = new Set(
Expand Down Expand Up @@ -439,16 +437,20 @@ const synchronizeProjectRecusal = async (
data: { assignmentVersion: { increment: 1 } },
});
}
await invalidateRankings(transaction, [
...sourceAssignments.map(assignment => ({
judgeId: input.judgeId,
categoryCode: assignment.categoryCode,
})),
...replacements.map(replacement => ({
judgeId: replacement.targetJudgeId,
categoryCode: sourceAssignments.find(item => item.id === replacement.sourceAssignmentId)?.categoryCode ?? "",
})),
].filter(pair => pair.categoryCode));
await invalidateRankings(
transaction,
[
...sourceAssignments.map(assignment => ({
judgeId: input.judgeId,
categoryCode: assignment.categoryCode,
})),
...replacements.map(replacement => ({
judgeId: replacement.targetJudgeId,
categoryCode:
sourceAssignments.find(item => item.id === replacement.sourceAssignmentId)?.categoryCode ?? "",
})),
].filter(pair => pair.categoryCode),
);
if (
input.reason &&
(!alreadyRecused || hadMissingCoverage || sourceAssignments.some(assignment => assignment.recusedAt === null))
Expand Down Expand Up @@ -1317,7 +1319,9 @@ export const judgingRouter = createTRPCRouter({
});
const excludedCategoryCodes = ALL_JUDGING_CATEGORY_CODES.filter(code => !allowed.has(code));
const existingExclusions = jsonStringArray(judge.exclusions);
const conflictingAllowed = request.allowedCategoryCodes.filter(code => existingExclusions.includes(code));
const conflictingAllowed = request.allowedCategoryCodes.filter(code =>
existingExclusions.includes(code),
);
if (conflictingAllowed.length)
throw new TRPCError({
code: "PRECONDITION_FAILED",
Expand Down Expand Up @@ -1957,7 +1961,9 @@ export const judgingRouter = createTRPCRouter({
for (const assignments of groups.values()) {
const first = assignments[0];
if (!first) continue;
const reason = assignments.find(assignment => assignment.recusalReason?.trim())?.recusalReason?.trim();
const reason = assignments
.find(assignment => assignment.recusalReason?.trim())
?.recusalReason?.trim();
if (!reason)
throw new TRPCError({
code: "PRECONDITION_FAILED",
Expand Down Expand Up @@ -2783,8 +2789,9 @@ export const judgingRouter = createTRPCRouter({
.map(item => ({
tableNumber: item.project.tableNumber,
name: item.project.name,
removedAssignments: item.project.assignments.filter(assignment => !assignment.completedAt)
.length,
removedAssignments: item.project.assignments.filter(
assignment => !assignment.completedAt,
).length,
}))
.sort((a, b) => a.tableNumber - b.tableNumber),
insufficient,
Expand Down Expand Up @@ -2941,10 +2948,7 @@ export const judgingRouter = createTRPCRouter({
judgeId: ctx.judge.id,
projectId: assignment.projectId,
reason,
editedAt: clampJudgingEditTime(
patch.fieldEditedAt.recusalReason ?? patch.editedAt,
now,
),
editedAt: clampJudgingEditTime(patch.fieldEditedAt.recusalReason ?? patch.editedAt, now),
operationId: patch.fieldOperationIds.recusalReason ?? patch.operationId,
now,
});
Expand Down Expand Up @@ -3336,13 +3340,17 @@ export const judgingRouter = createTRPCRouter({
if (numericDifference !== 0) return numericDifference;
return a.tableNumber - b.tableNumber || a.projectId.localeCompare(b.projectId);
});
// ⚡ Bolt: Pre-compute positions and score counts to avoid O(n^2) lookups
const positionsByProjectId = new Map(scored.map((item, index) => [item.projectId, index]));
const scoreCounts = new Map<number, number>();
for (const item of scored) {
if (item.numericAggregate !== null) {
scoreCounts.set(item.numericAggregate, (scoreCounts.get(item.numericAggregate) ?? 0) + 1);
}
}
return items.map(item => {
const position = scored.findIndex(candidate => candidate.projectId === item.projectId);
const tied = scored.some(
candidate =>
candidate.projectId !== item.projectId &&
candidate.numericAggregate === item.numericAggregate,
);
const position = positionsByProjectId.get(item.projectId) ?? -1;
const tied = item.numericAggregate !== null && (scoreCounts.get(item.numericAggregate) ?? 0) > 1;
return {
...item,
officialPosition: position < 0 || tied ? null : position + 1,
Expand All @@ -3351,6 +3359,12 @@ export const judgingRouter = createTRPCRouter({
};
});
});
// ⚡ Bolt: Pre-group assignments by project and category to avoid O(n^2) filter lookups
const assignmentsByProjectAndCategory = Map.groupBy(
assignments,
assignment => `${assignment.projectId}:${assignment.categoryCode}`,
);

const benchmarks = [...Map.groupBy(assignments, assignment => assignment.judgeId).values()].map(
judgeAssignments => {
const judge = judgeAssignments[0]?.judge;
Expand All @@ -3361,13 +3375,10 @@ export const judgingRouter = createTRPCRouter({
const sharedDifferences = judgeAssignments.flatMap(assignment => {
const score = numericForAssignment(assignment);
if (score === null) return [];
const peers = assignments
.filter(
candidate =>
candidate.judgeId !== assignment.judgeId &&
candidate.projectId === assignment.projectId &&
candidate.categoryCode === assignment.categoryCode,
)
const peers = (
assignmentsByProjectAndCategory.get(`${assignment.projectId}:${assignment.categoryCode}`) ?? []
)
.filter(candidate => candidate.judgeId !== assignment.judgeId)
.map(numericForAssignment)
.filter((value): value is number => value !== null);
return peers.length ? [score - peers.reduce((sum, value) => sum + value, 0) / peers.length] : [];
Expand Down
Loading