Skip to content

⚡ Optimize Date parsing in yearInReviewUtils#363

Open
is0692vs wants to merge 3 commits into
mainfrom
optimize-date-parsing-9057842699280315747
Open

⚡ Optimize Date parsing in yearInReviewUtils#363
is0692vs wants to merge 3 commits into
mainfrom
optimize-date-parsing-9057842699280315747

Conversation

@is0692vs

@is0692vs is0692vs commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

💡 What: Replaced the expensive new Date() allocation inside loops used to calculate the day of the week from ISO date strings with a custom, mathematically-based parsing approach using Sakamoto's algorithm.

🎯 Why: Creating new Date() objects dynamically inside a loop creates significant memory allocation pressure and negatively impacts execution speed, especially when dealing with large volumes of commits or contributions (like generating heatmaps). Sakamoto's algorithm avoids this completely for perfectly structured ISO dates.

📊 Measured Improvement:

  • Baseline: buildHourlyHeatmapFromCommitDates processing 1,000,000 dates took ~184ms.
  • Improved: buildHourlyHeatmapFromCommitDates processing 1,000,000 dates takes ~164ms.
    This represents roughly an 11% overall speedup, and eliminates massive garbage collection overhead previously triggered by allocating thousands of temporary Date objects.

PR created automatically by Jules for task 9057842699280315747 started by @is0692vs

Greptile Summary

本 PR は buildHourlyHeatmapFromCommitDates および getMostActiveDayFromCalendar 内の曜日計算において、new Date() オブジェクトの生成をループ内で行う代わりに、Sakamoto's Algorithm を用いた純数学的な計算(getWeekdayFromDateString)を導入してパフォーマンスを改善します。

  • 新関数 getWeekdayFromDateStringYYYY-MM-DD 形式の文字列を直接解析し new Date() の割り当てを回避。有効なフォーマットでない場合は既存の Date コンストラクタにフォールバックする安全な設計になっています。
  • buildHourlyHeatmapFromCommitDates では既存の dayCache と組み合わせることでアロケーションとGCの両方を削減し、getMostActiveDayFromCalendar でも同様に各エントリに対して Date オブジェクト生成を省略しています。

Confidence Score: 4/5

実際の GitHub データ(2008年以降)に対しては正しく動作し、new Date() 呼び出しを減らす意図通りの最適化が実現されています。

アルゴリズム実装は実用的な日付範囲では正確です。ただし JavaScript の % 演算子が負数に対して負の値を返す特性により、年 "0000" の1月1日のような極端なケースで誤った結果(-1)が返り、heatmap[-1][hour] へのアクセスで TypeError が起きる可能性があります。入力バリデーションがこの年を明示的に除外していない点が懸念です。

src/lib/yearInReviewUtils.ts の getWeekdayFromDateString 関数(特にモジュロ演算の行)に注目してください。

Important Files Changed

Filename Overview
src/lib/yearInReviewUtils.ts Sakamoto's algorithm を使った曜日計算の最適化。実用上は正しく動作するが、JavaScript の % 演算子が負の値を返す可能性(理論的エッジケース)がある。

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[ISO 8601 date string input] --> B{Standard format check}
    B -- Non-standard --> C[parseFallbackDate]
    B -- Standard --> D[datePart = slice 0 to 10]
    D --> E{dayCache hit?}
    E -- Hit --> H[Parse hour]
    E -- Miss --> F[getWeekdayFromDateString]
    F --> G{Result null?}
    G -- Not null fast path --> I[day = calculatedDay]
    G -- null fallback --> J[new Date constructor]
    J --> K{NaN?}
    K -- NaN --> C
    K -- Valid --> L[day = date.getUTCDay]
    I --> M[dayCache.set]
    L --> M
    M --> H
    H --> N{Valid hour and ends with Z?}
    N -- Invalid --> C
    N -- Valid --> O[heatmap day hour += 1]
Loading
Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 1
src/lib/yearInReviewUtils.ts:50
JavaScript の `%` 演算子は被除数が負の場合に負の値を返します。`y``0` の場合(例: 年 "0000"、1月 or 2月)、`y -= 1``-1` になり、合計が負になる可能性があります(例: "0000-01-01" → `-1 % 7 = -1`)。実際の GitHub データでこの年の値が現れることはほぼありませんが、バリデーションが年 "0000" を弾いていないため、`heatmap[-1][hour]` へのアクセスで `TypeError` が発生する可能性があります。`((sum % 7) + 7) % 7` を使って非負の値を保証することを推奨します。

```suggestion
    return ((y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) + SAKAMOTO_T_ARRAY[m - 1] + d) % 7 + 7) % 7;
```

Reviews (1): Last reviewed commit: "perf: optimize Date parsing in yearInRev..." | Re-trigger Greptile

Greptile also left 1 inline comment on this PR.

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@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

vercel Bot commented Jun 12, 2026

Copy link
Copy Markdown

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

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
github-user-summary Ignored Ignored Jun 12, 2026 7:41am

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@is0692vs, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 8 minutes and 21 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more credits in the billing tab to continue.

⌛ How to resolve this issue?

After more reviews become available, 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 include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3c90c636-61cb-4bdf-9b43-bff294b8a67a

📥 Commits

Reviewing files that changed from the base of the PR and between a475ecb and 175f4f9.

📒 Files selected for processing (2)
  • src/lib/__tests__/yearInReviewUtils.test.ts
  • src/lib/yearInReviewUtils.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch optimize-date-parsing-9057842699280315747

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.

@dosubot dosubot Bot added the enhancement New feature or request label Jun 12, 2026
@codecov

codecov Bot commented Jun 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.66667% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/lib/yearInReviewUtils.ts 91.66% 2 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

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

Copy link
Copy Markdown

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 introduces a fast-path mathematical calculation for determining the day of the week from a date string using Sakamoto's Algorithm (getWeekdayFromDateString). This is integrated into buildHourlyHeatmapFromCommitDates and getMostActiveDayFromCalendar to optimize performance, falling back to standard Date parsing if the fast-path fails. However, the new validation logic in getWeekdayFromDateString allows invalid dates (such as February 30th) to pass through, which could corrupt heatmap data. A code suggestion has been provided to properly validate the maximum number of days for each month, including leap years.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +42 to +44
if (m < 1 || m > 12 || d < 1 || d > 31) {
return null;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

The current implementation of getWeekdayFromDateString only checks if the day d is between 1 and 31, and the month m is between 1 and 12. This allows invalid dates (such as 2023-02-30 or 2023-04-31) to be successfully parsed and assigned a weekday. Consequently, these invalid dates bypass the fallback logic and corrupt the heatmap data.

To ensure correctness, we should validate the maximum number of days allowed for each month, taking leap years into account for February.

Suggested change
if (m < 1 || m > 12 || d < 1 || d > 31) {
return null;
}
if (m < 1 || m > 12 || d < 1) {
return null;
}
if (m === 2) {
const isLeap = (y % 4 === 0 && y % 100 !== 0) || (y % 400 === 0);
if (d > (isLeap ? 29 : 28)) return null;
} else if (m === 4 || m === 6 || m === 9 || m === 11) {
if (d > 30) return null;
} else {
if (d > 31) return null;
}

Comment thread src/lib/yearInReviewUtils.ts Outdated
y -= 1;
}

return (y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) + SAKAMOTO_T_ARRAY[m - 1] + d) % 7;

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.

P2 JavaScript の % 演算子は被除数が負の場合に負の値を返します。y0 の場合(例: 年 "0000"、1月 or 2月)、y -= 1-1 になり、合計が負になる可能性があります(例: "0000-01-01" → -1 % 7 = -1)。実際の GitHub データでこの年の値が現れることはほぼありませんが、バリデーションが年 "0000" を弾いていないため、heatmap[-1][hour] へのアクセスで TypeError が発生する可能性があります。((sum % 7) + 7) % 7 を使って非負の値を保証することを推奨します。

Suggested change
return (y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) + SAKAMOTO_T_ARRAY[m - 1] + d) % 7;
return ((y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) + SAKAMOTO_T_ARRAY[m - 1] + d) % 7 + 7) % 7;
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/lib/yearInReviewUtils.ts
Line: 50

Comment:
JavaScript の `%` 演算子は被除数が負の場合に負の値を返します。`y``0` の場合(例: 年 "0000"、1月 or 2月)、`y -= 1``-1` になり、合計が負になる可能性があります(例: "0000-01-01" → `-1 % 7 = -1`)。実際の GitHub データでこの年の値が現れることはほぼありませんが、バリデーションが年 "0000" を弾いていないため、`heatmap[-1][hour]` へのアクセスで `TypeError` が発生する可能性があります。`((sum % 7) + 7) % 7` を使って非負の値を保証することを推奨します。

```suggestion
    return ((y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) + SAKAMOTO_T_ARRAY[m - 1] + d) % 7 + 7) % 7;
```

How can I resolve this? If you propose a fix, please make it concise.

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@pull-request-size pull-request-size Bot added size/L and removed size/M labels Jun 12, 2026
…havior

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant