diff --git a/app/features/tournament-bracket/core/Progression.ts b/app/features/tournament-bracket/core/Progression.ts index 3efbff1e0..6415e6090 100644 --- a/app/features/tournament-bracket/core/Progression.ts +++ b/app/features/tournament-bracket/core/Progression.ts @@ -850,30 +850,49 @@ export function bracketIdxsForStandings(progression: ParsedBracket[]) { }, ); - return withoutUnderground.sort((a, b) => { - const minSourcedPlacementA = Math.min( - ...(progression[a].sources?.flatMap((s) => s.placements) ?? [ - Number.POSITIVE_INFINITY, - ]), - ); - const minSourcedPlacementB = Math.min( - ...(progression[b].sources?.flatMap((s) => s.placements) ?? [ - Number.POSITIVE_INFINITY, - ]), - ); + const minSourcedPlacements = new Map( + withoutUnderground.map((idx) => [ + idx, + minSourcedPlacement(progression, idx), + ]), + ); - if (minSourcedPlacementA === minSourcedPlacementB) { + return [...withoutUnderground].sort((a, b) => { + const minA = minSourcedPlacements.get(a)!; + const minB = minSourcedPlacements.get(b)!; + + if (minA === minB) { return a - b; } - return minSourcedPlacementA - minSourcedPlacementB; + return minA - minB; }); } +function minSourcedPlacement( + progression: ParsedBracket[], + bracketIdx: number, +): number { + const sources = progression[bracketIdx].sources; + if (!sources || sources.length === 0) return Number.POSITIVE_INFINITY; + + let min = Number.POSITIVE_INFINITY; + for (const source of sources) { + for (const placement of source.placements) { + if (placement < min) min = placement; + } + } + return min; +} + export function bracketsReachableFrom( bracketIdx: number, progression: ParsedBracket[], + visited: Set = new Set(), ): number[] { + if (visited.has(bracketIdx)) return []; + visited.add(bracketIdx); + const result = [bracketIdx]; for (const [newBracketIdx, bracket] of progression.entries()) { @@ -881,7 +900,9 @@ export function bracketsReachableFrom( for (const source of bracket.sources) { if (source.bracketIdx === bracketIdx) { - result.push(...bracketsReachableFrom(newBracketIdx, progression)); + result.push( + ...bracketsReachableFrom(newBracketIdx, progression, visited), + ); } } }