Skip to content

⚡ Bolt: Replace O(n²) nested loop with O(n) map accumulation#138

Open
anyulled wants to merge 3 commits intomainfrom
bolt-opt-schedule-o1-10590448881623300
Open

⚡ Bolt: Replace O(n²) nested loop with O(n) map accumulation#138
anyulled wants to merge 3 commits intomainfrom
bolt-opt-schedule-o1-10590448881623300

Conversation

@anyulled
Copy link
Copy Markdown
Owner

@anyulled anyulled commented Apr 1, 2026

💡 What: Replaced the array spread operator ([...existing, session]) with push() when building the sessionsByTime map in hooks/useSchedule.ts.
🎯 Why: The previous implementation created a new array on every iteration within a nested loop, resulting in O(N²) time complexity and unnecessary memory allocations.
📊 Impact: Changes the data aggregation from O(N²) to O(N) amortized time, lowering Garbage Collection overhead.
🔬 Measurement: Run the test suite (npm run test) and confirm tests pass. Time complexity is mathematically reduced.


PR created automatically by Jules for task 10590448881623300 started by @anyulled

Summary by CodeRabbit

  • New Features

    • Added schedule management system for organizing and displaying sessions by time slots and room locations, with integrated data fetching and caching
  • Refactor

    • Optimized performance of schedule session grouping logic for improved processing efficiency

@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@vercel
Copy link
Copy Markdown

vercel bot commented Apr 1, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
devbcn Ready Ready Preview, Comment Apr 1, 2026 5:21pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 1, 2026

Warning

Rate limit exceeded

@anyulled has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 25 minutes and 4 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 25 minutes and 4 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 575e3099-cb70-425f-8f22-9facbab215ce

📥 Commits

Reviewing files that changed from the base of the PR and between 0cbec96 and 9a21fe3.

📒 Files selected for processing (2)
  • .gitignore
  • hooks/useSchedule.ts
📝 Walkthrough

Walkthrough

The PR modifies the schedule grouping logic in hooks/useSchedule.ts to use in-place array mutation with push instead of spread operator, and adds a new hooks/useSchedule.ts.orig file containing TypeScript interfaces (GridSession, GridRoom, GridSchedule, TimeSlot, DailySchedule) and a cached async fetcher function that retrieves and transforms grid-based scheduling data.

Changes

Cohort / File(s) Summary
Schedule Hooks
hooks/useSchedule.ts, hooks/useSchedule.ts.orig
Modified grouping logic to use in-place push() mutation for array accumulation instead of spread operator; added new module with schedule data interfaces and getSchedule(year) fetcher that retrieves schedule from Sessionize endpoint, transforms raw grid structure into DailySchedule[] with aggregated timeSlots, and includes error handling returning empty array on failure.

Sequence Diagram

sequenceDiagram
    participant Client as Client Code
    participant getSchedule as getSchedule()
    participant Config as getEditionConfig()
    participant API as Sessionize API
    participant Transform as Data Transform
    
    Client->>getSchedule: getSchedule(year)
    getSchedule->>Config: getEditionConfig(year)
    Config-->>getSchedule: edition config
    getSchedule->>API: fetch schedule from /view/GridSmart
    API-->>getSchedule: JSON response
    getSchedule->>Transform: validate & group by time
    Transform->>Transform: aggregate sessions by room<br/>sort by room & time
    Transform-->>getSchedule: DailySchedule[]
    getSchedule-->>Client: schedule data
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • #24: Modifies the same getSchedule implementation in hooks/useSchedule.ts with related changes to array handling and React cache wrapping.
  • #105: Applies the same array mutation optimization pattern (replacing spread-based grouping with push) across different hooks files.

Suggested labels

size/size/XXL

Poem

🐰 Arrays dance in groups of time,
From spread to push, a change sublime,
New interfaces, fetchers made,
Grid schedules gracefully displayed! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main optimization change: replacing an O(n²) nested loop approach with O(n) map accumulation in the sessionsByTime grouping logic.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bolt-opt-schedule-o1-10590448881623300

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@qodo-code-review
Copy link
Copy Markdown

Review Summary by Qodo

Optimize schedule session aggregation with O(n) map accumulation

✨ Enhancement

Grey Divider

Walkthroughs

Description
• Optimize session aggregation from O(n²) to O(n) complexity
• Replace array spread operator with direct array mutation
• Eliminate unnecessary array allocations in nested loop
• Reduce garbage collection overhead during schedule processing
Diagram
flowchart LR
  A["Nested loop over rooms and sessions"] --> B["Get existing sessions from map"]
  B --> C["Check if sessions exist"]
  C -->|No| D["Create new array with session"]
  C -->|Yes| E["Push session to existing array"]
  D --> F["Set in map"]
  E --> F
  F --> G["O(n) time complexity achieved"]
Loading

Grey Divider

File Changes

1. hooks/useSchedule.ts Performance optimization +7/-2

Replace O(n²) spread with O(n) push mutation

• Replaced array spread operator [...existing, session] with conditional logic
• Initialize new array directly when no existing sessions found
• Use push() method to mutate existing array instead of creating new one
• Added explanatory comment about O(n²) spread overhead optimization

hooks/useSchedule.ts


2. hooks/useSchedule.ts.orig Miscellaneous +87/-0

Original implementation reference file

• New file containing the complete original implementation
• Includes all type definitions and the full getSchedule function
• Serves as reference for the optimized version

hooks/useSchedule.ts.orig


Grey Divider

Qodo Logo

@qodo-code-review
Copy link
Copy Markdown

qodo-code-review bot commented Apr 1, 2026

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider


Action required

1. Accidental .orig file 🐞 Bug ⚙ Maintainability
Description
The PR adds hooks/useSchedule.ts.orig, which is a full duplicate of hooks/useSchedule.ts exporting
the same getSchedule function and types. Keeping a second copy increases maintenance risk (future
edits can diverge) and creates a footgun where someone can accidentally import/modify the wrong
file.
Code

hooks/useSchedule.ts.orig[R1-5]

+import { getEditionConfig } from "@/config/editions";
+import { format, parseISO } from "date-fns";
+import { cache } from "react";
+
+export interface GridSession {
Evidence
hooks/useSchedule.ts.orig duplicates the same module header/types as hooks/useSchedule.ts, and there
is no gitignore rule that would normally prevent editor/backup *.orig artifacts from being
committed, so this file will remain tracked and can drift from the real implementation.

hooks/useSchedule.ts.orig[1-25]
hooks/useSchedule.ts[1-10]
.gitignore[1-143]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`hooks/useSchedule.ts.orig` was added to the repo as a duplicate copy of `hooks/useSchedule.ts`. This looks like an editor/automation artifact and should not be committed.

### Issue Context
Leaving duplicate source files around makes future changes error-prone (the two copies can diverge) and increases the risk of accidental imports/usage.

### Fix Focus Areas
- hooks/useSchedule.ts.orig[1-87]
- .gitignore[1-143]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request optimizes the getSchedule function by replacing array spreading with direct mutation to avoid performance overhead. Feedback suggests removing an accidentally committed .orig file and cleaning up tool-specific branding and redundant explanations within the code comments.

Comment on lines +1 to +87
import { getEditionConfig } from "@/config/editions";
import { format, parseISO } from "date-fns";
import { cache } from "react";

export interface GridSession {
id: string;
title: string;
description: string | null;
startsAt: string;
endsAt: string;
isServiceSession: boolean;
isPlenumSession: boolean;
speakers: { id: string; name: string }[];
roomId: number;
room: string;
status: string | null;
}

export interface GridRoom {
id: number;
name: string;
sessions: GridSession[];
hasOnlyPlenumSessions: boolean;
}

export interface GridSchedule {
date: string;
isDefault: boolean;
rooms: GridRoom[];
}

export interface TimeSlot {
time: string;
sessions: GridSession[];
}

export interface DailySchedule {
date: string;
rooms: GridRoom[];
timeSlots: TimeSlot[];
}

export const getSchedule = cache(async (year: string | number): Promise<DailySchedule[]> => {
const config = getEditionConfig(year);

const url = `${config.sessionizeUrl}/view/GridSmart`;

try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch schedule: ${response.statusText}`);
}
const data: GridSchedule[] = await response.json();

return data.map((day) => {
const sessionsByTime = new Map<string, GridSession[]>();

day.rooms.forEach((room) => {
room.sessions.forEach((session) => {
const timeKey = format(parseISO(session.startsAt), "HH:mm");
const existing = sessionsByTime.get(timeKey);
if (!existing) {
sessionsByTime.set(timeKey, [session]);
} else {
existing.push(session);
}
});
});

const timeSlots: TimeSlot[] = Array.from(sessionsByTime.entries())
.map(([time, sessions]) => ({
time,
sessions: sessions.sort((a, b) => a.room.localeCompare(b.room)),
}))
.sort((a, b) => a.time.localeCompare(b.time));

return {
date: day.date,
rooms: day.rooms,
timeSlots,
};
});
} catch (error) {
console.error("Error fetching schedule:", error);
return [];
}
});
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This file appears to be a temporary artifact (likely from a merge conflict or a development tool) and should not be committed to the repository.

Comment on lines +1 to +5
import { getEditionConfig } from "@/config/editions";
import { format, parseISO } from "date-fns";
import { cache } from "react";

export interface GridSession {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

1. Accidental .orig file 🐞 Bug ⚙ Maintainability

The PR adds hooks/useSchedule.ts.orig, which is a full duplicate of hooks/useSchedule.ts exporting
the same getSchedule function and types. Keeping a second copy increases maintenance risk (future
edits can diverge) and creates a footgun where someone can accidentally import/modify the wrong
file.
Agent Prompt
### Issue description
`hooks/useSchedule.ts.orig` was added to the repo as a duplicate copy of `hooks/useSchedule.ts`. This looks like an editor/automation artifact and should not be committed.

### Issue Context
Leaving duplicate source files around makes future changes error-prone (the two copies can diverge) and increases the risk of accidental imports/usage.

### Fix Focus Areas
- hooks/useSchedule.ts.orig[1-87]
- .gitignore[1-143]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
hooks/useSchedule.ts.orig (1)

1-87: Please remove committed backup file hooks/useSchedule.ts.orig.

This duplicates production logic from hooks/useSchedule.ts and will drift over time. Keeping only one source of truth reduces maintenance risk.

Suggested cleanup
diff --git a/hooks/useSchedule.ts.orig b/hooks/useSchedule.ts.orig
deleted file mode 100644
--- a/hooks/useSchedule.ts.orig
+++ /dev/null
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@hooks/useSchedule.ts.orig` around lines 1 - 87, Remove the committed backup
file hooks/useSchedule.ts.orig which duplicates the production logic (see
getSchedule in hooks/useSchedule.ts); delete the .orig file from the repo (e.g.,
git rm --cached or git rm and commit the deletion) so only hooks/useSchedule.ts
remains as the single source of truth, and ensure there are no imports or
references to hooks/useSchedule.ts.orig before pushing the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@hooks/useSchedule.ts.orig`:
- Around line 1-87: Remove the committed backup file hooks/useSchedule.ts.orig
which duplicates the production logic (see getSchedule in hooks/useSchedule.ts);
delete the .orig file from the repo (e.g., git rm --cached or git rm and commit
the deletion) so only hooks/useSchedule.ts remains as the single source of
truth, and ensure there are no imports or references to
hooks/useSchedule.ts.orig before pushing the change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e2c580dc-4689-4234-9931-e5fcaf22d8bb

📥 Commits

Reviewing files that changed from the base of the PR and between cdce2d3 and 0cbec96.

📒 Files selected for processing (2)
  • hooks/useSchedule.ts
  • hooks/useSchedule.ts.orig

@anyulled
Copy link
Copy Markdown
Owner Author

anyulled commented Apr 1, 2026

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

Issue description

hooks/useSchedule.ts.orig was added to the repo as a duplicate copy of hooks/useSchedule.ts. This looks like an editor/automation artifact and should not be committed.

Issue Context

Leaving duplicate source files around makes future changes error-prone (the two copies can diverge) and increases the risk of accidental imports/usage.

Fix Focus Areas

  • hooks/useSchedule.ts.orig[1-87]
  • .gitignore[1-143]

anyulled and others added 2 commits April 1, 2026 19:16
Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@anyulled anyulled force-pushed the bolt-opt-schedule-o1-10590448881623300 branch from ec4532e to 11159b1 Compare April 1, 2026 17:16
@google-labs-jules
Copy link
Copy Markdown
Contributor

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

Issue description

hooks/useSchedule.ts.orig was added to the repo as a duplicate copy of hooks/useSchedule.ts. This looks like an editor/automation artifact and should not be committed.

Issue Context

Leaving duplicate source files around makes future changes error-prone (the two copies can diverge) and increases the risk of accidental imports/usage.

Fix Focus Areas

  • hooks/useSchedule.ts.orig[1-87]
  • .gitignore[1-143]

I have removed hooks/useSchedule.ts.orig and added *.orig to .gitignore to prevent this from happening in the future.

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant