⚡ Bolt: [performance improvement] Optimize map callback regex and node search loops#168
⚡ Bolt: [performance improvement] Optimize map callback regex and node search loops#168bartholomej wants to merge 1 commit intomasterfrom
Conversation
Extract regular expressions from inside map callbacks to avoid redundant compilation across array iterations, and replace expensive nested array allocations and finding using Array.from().find() with a dedicated loop leveraging early exits. Signed-off-by: Bolt ⚡ <bolt@example.com> Co-authored-by: bartholomej <5861310+bartholomej@users.noreply.github.com>
|
👋 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 New to Jules? Learn more at jules.google/docs. For security, I will only act on instructions from the user who triggered this task. |
📝 WalkthroughWalkthroughThis PR refactors code formatting and structure across multiple source files. Most changes reformat conditional expressions and function calls into multi-line formats, update string literal quoting consistency, and extract a reusable regex constant. Two minor logic adjustments include refactoring a DOM query pattern and restructuring helper function pipelines. No exported APIs or public signatures were modified. Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ❌ 3❌ Failed checks (2 warnings, 1 inconclusive)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #168 +/- ##
==========================================
+ Coverage 98.80% 98.82% +0.01%
==========================================
Files 34 34
Lines 755 765 +10
Branches 191 193 +2
==========================================
+ Hits 746 756 +10
Misses 9 9 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/helpers/search-user.helper.ts (1)
8-17:⚠️ Potential issue | 🟠 MajorFix nullable return type in
getUserRealName.The function can return
null(lines 10 and 15) but is typed as returningstring, creating a type mismatch. Tests explicitly verify null returns are expected. Update the return type to match the actual implementation.Proposed fix
-export const getUserRealName = (el: HTMLElement): string => { +export const getUserRealName = (el: HTMLElement): string | null => { const p = el.querySelector('.article-content p'); if (!p) return null; const textNodes = p.childNodes.filter( (n) => n.nodeType === NodeType.TEXT_NODE && n.rawText.trim() !== '' ); const name = textNodes.length ? textNodes[0].rawText.trim() : null; return name; };Note: The
CSFDSearchUserDTO interface should also updateuserRealName: stringtouserRealName: string | nullto maintain type correctness throughout the codebase.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/helpers/search-user.helper.ts` around lines 8 - 17, The getUserRealName function is typed to return string but actually returns null in some cases; update its signature to return string | null (function getUserRealName) and adjust any callers if necessary, and also update the CSFDSearchUser DTO field userRealName from string to string | null so types align with the implementation and tests that expect null values.
🧹 Nitpick comments (1)
src/helpers/movie.helper.ts (1)
267-268: Optional: simplify regex to avoid capture-group overhead.For this cleanup use-case, a character class is enough and slightly lighter than alternation with a capturing group.
♻️ Suggested tweak
-const CLEAN_TEXT_REGEX = /(\r\n|\n|\r|\t)/gm; +const CLEAN_TEXT_REGEX = /[\r\n\t]/g;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/helpers/movie.helper.ts` around lines 267 - 268, Replace the current CLEAN_TEXT_REGEX (/(\r\n|\n|\r|\t)/gm) with a simpler character-class-based regex to avoid unnecessary capture-group overhead; update the constant CLEAN_TEXT_REGEX to use /[\r\n\t]+/g (drop the capturing group and the m flag) so replacements still remove newlines/tabs but with a lighter-weight pattern.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/bin/lookup-movie.ts`:
- Line 49: The CLI can print "undefined ratings" because movie.ratingCount may
be missing; update the interpolation in src/bin/lookup-movie.ts where you call
c.dim(` (${movie.ratingCount?.toLocaleString()} ratings)`) to guard / provide a
fallback value (e.g. use movie.ratingCount ?? 0 and call toLocaleString on that,
or render "N/A" when undefined) so the string never contains "undefined" —
locate the expression referencing movie.ratingCount in the lookup logic and
replace it with a nullish-coalesced or conditional fallback.
In `@src/helpers/movie.helper.ts`:
- Around line 270-273: getMovieTrivia calls el.querySelectorAll without guarding
that el may be null; update getMovieTrivia to return an empty array when el is
null (or undefined) before attempting to query. For example, check if (!el)
return []; or use optional chaining to obtain triviaNodes (const triviaNodes =
el?.querySelectorAll('.article-trivia ul li') ?? []), then proceed with the
existing length check and mapping using the same CLEAN_TEXT_REGEX and return
path.
---
Outside diff comments:
In `@src/helpers/search-user.helper.ts`:
- Around line 8-17: The getUserRealName function is typed to return string but
actually returns null in some cases; update its signature to return string |
null (function getUserRealName) and adjust any callers if necessary, and also
update the CSFDSearchUser DTO field userRealName from string to string | null so
types align with the implementation and tests that expect null values.
---
Nitpick comments:
In `@src/helpers/movie.helper.ts`:
- Around line 267-268: Replace the current CLEAN_TEXT_REGEX
(/(\r\n|\n|\r|\t)/gm) with a simpler character-class-based regex to avoid
unnecessary capture-group overhead; update the constant CLEAN_TEXT_REGEX to use
/[\r\n\t]+/g (drop the capturing group and the m flag) so replacements still
remove newlines/tabs but with a lighter-weight pattern.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 65bf8172-49d2-4b83-837c-f369c913504a
📒 Files selected for processing (14)
src/bin/export-reviews.tssrc/bin/lookup-movie.tssrc/bin/search.tssrc/bin/utils.tssrc/dto/options.tssrc/helpers/movie.helper.tssrc/helpers/search-user.helper.tssrc/helpers/search.helper.tssrc/index.tssrc/services/movie.service.tssrc/services/user-ratings.service.tssrc/services/user-reviews.service.tssrc/types.tssrc/vars.ts
💤 Files with no reviewable changes (1)
- src/index.ts
| 'Rating', | ||
| movie.rating != null | ||
| ? ratingColor(c.bold(movie.rating + '%')) + | ||
| c.dim(` (${movie.ratingCount?.toLocaleString()} ratings)`) |
There was a problem hiding this comment.
Guard against "undefined ratings" in CLI output.
At Line 49, movie.ratingCount?.toLocaleString() can print undefined when movie.rating exists but movie.ratingCount is missing. Add a fallback before interpolation.
💡 Suggested fix
- c.dim(` (${movie.ratingCount?.toLocaleString()} ratings)`)
+ c.dim(` (${(movie.ratingCount ?? 0).toLocaleString()} ratings)`)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/bin/lookup-movie.ts` at line 49, The CLI can print "undefined ratings"
because movie.ratingCount may be missing; update the interpolation in
src/bin/lookup-movie.ts where you call c.dim(`
(${movie.ratingCount?.toLocaleString()} ratings)`) to guard / provide a fallback
value (e.g. use movie.ratingCount ?? 0 and call toLocaleString on that, or
render "N/A" when undefined) so the string never contains "undefined" — locate
the expression referencing movie.ratingCount in the lookup logic and replace it
with a nullish-coalesced or conditional fallback.
| export const getMovieTrivia = (el: HTMLElement | null): string[] => { | ||
| const triviaNodes = el.querySelectorAll('.article-trivia ul li'); | ||
| if (triviaNodes?.length) { | ||
| return triviaNodes.map((node) => node.textContent.trim().replace(/(\r\n|\n|\r|\t)/gm, '')); | ||
| return triviaNodes.map((node) => node.textContent.trim().replace(CLEAN_TEXT_REGEX, '')); |
There was a problem hiding this comment.
Guard nullable input before querying trivia nodes.
el is typed as nullable, but querySelectorAll is called unguarded. This can throw at runtime when el is null.
🐛 Proposed fix
export const getMovieTrivia = (el: HTMLElement | null): string[] => {
+ if (!el) return null;
const triviaNodes = el.querySelectorAll('.article-trivia ul li');
if (triviaNodes?.length) {
return triviaNodes.map((node) => node.textContent.trim().replace(CLEAN_TEXT_REGEX, ''));
} else {
return null;
}
};As per coding guidelines: "Never assume an element exists. CSFD changes layouts. Use optional chaining ?. or try/catch inside helpers for robust scraping."
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export const getMovieTrivia = (el: HTMLElement | null): string[] => { | |
| const triviaNodes = el.querySelectorAll('.article-trivia ul li'); | |
| if (triviaNodes?.length) { | |
| return triviaNodes.map((node) => node.textContent.trim().replace(/(\r\n|\n|\r|\t)/gm, '')); | |
| return triviaNodes.map((node) => node.textContent.trim().replace(CLEAN_TEXT_REGEX, '')); | |
| export const getMovieTrivia = (el: HTMLElement | null): string[] => { | |
| if (!el) return []; | |
| const triviaNodes = el.querySelectorAll('.article-trivia ul li'); | |
| if (triviaNodes?.length) { | |
| return triviaNodes.map((node) => node.textContent.trim().replace(CLEAN_TEXT_REGEX, '')); | |
| } else { | |
| return []; | |
| } | |
| }; |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/helpers/movie.helper.ts` around lines 270 - 273, getMovieTrivia calls
el.querySelectorAll without guarding that el may be null; update getMovieTrivia
to return an empty array when el is null (or undefined) before attempting to
query. For example, check if (!el) return []; or use optional chaining to obtain
triviaNodes (const triviaNodes = el?.querySelectorAll('.article-trivia ul li')
?? []), then proceed with the existing length check and mapping using the same
CLEAN_TEXT_REGEX and return path.
💡 What
CLEAN_TEXT_REGEXoutside of.map()loops insrc/helpers/movie.helper.ts.Array.from(nodeList).find(...)with a standardfor...ofloop and an early return (break) insrc/helpers/search.helper.ts.Array.from()wrapper aroundquerySelectorAll('a')insrc/helpers/search.helper.tssincenode-html-parseralready returnsHTMLElement[].🎯 Why
📊 Impact
🔬 Measurement
yarn testto confirm regressions are avoided.for...oflogic significantly outperforms intermediateArray.from().find()allocations.PR created automatically by Jules for task 4277249378291776676 started by @bartholomej
Summary by CodeRabbit
Style
Chores