-
Notifications
You must be signed in to change notification settings - Fork 5
Add helper.ts #69
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add helper.ts #69
Conversation
WalkthroughA new TypeScript helper module has been added, introducing five utility functions: string formatting, sum calculation for number arrays, email validation, function debouncing, and array chunking. Each function is exported and designed to handle common utility scenarios with standard input assumptions. Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~7 minutes Poem
Pre-Merge Checks (3 warnings)❌ Failed Checks (3 warnings)
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. ✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 5
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
helper.ts
(1 hunks)
🧰 Additional context used
🔍 MCP Research (2 servers)
Context7: functions.resolve-library-id: No exact or closely matching library named "helper.ts" found; multiple helper-related libraries returned but none matching the described TypeScript helper module with functions formatString, calculateSum, isValidEmail, debounce, and chunk.
Linear: - Issue ENG-2040 titled "Add TypeScript helper functions" relates to adding helper functions in helper.ts but states calculateSum should NOT be included as it exists elsewhere (Issue ID 84652a3b-d55d-4894-9526-20eade880be8, https://linear.app/coderabbit/issue/ENG-2040/add-typescript-helper-functions)
- No documents or records specifically named or containing "helper.ts" were found in documentation or workspace (list_documents, get_document)
- No comments or discussions beyond initial notes were found on issue ENG-2040 (list_comments, get_issue)
export function formatString(input: string): string { | ||
return input.trim().toLowerCase().replace(/\s+/g, '-'); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add input validation and consider edge cases.
The function lacks input validation and could produce unexpected results with multiple consecutive whitespace characters.
Consider this improved implementation:
export function formatString(input: string): string {
+ if (!input || typeof input !== 'string') {
+ return '';
+ }
- return input.trim().toLowerCase().replace(/\s+/g, '-');
+ return input.trim().toLowerCase().replace(/\s+/g, '-').replace(/-+/g, '-');
}
This handles null/undefined inputs and prevents multiple consecutive hyphens.
📝 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 function formatString(input: string): string { | |
return input.trim().toLowerCase().replace(/\s+/g, '-'); | |
} | |
export function formatString(input: string): string { | |
if (!input || typeof input !== 'string') { | |
return ''; | |
} | |
return input | |
.trim() | |
.toLowerCase() | |
.replace(/\s+/g, '-') | |
.replace(/-+/g, '-'); | |
} |
🤖 Prompt for AI Agents
In helper.ts at lines 1 to 3, the formatString function lacks input validation
and does not handle edge cases like null or undefined inputs or multiple
consecutive whitespace characters properly. Add a check at the start to return
an empty string or handle null/undefined inputs gracefully. Modify the
replacement logic to ensure multiple consecutive whitespace characters do not
result in multiple consecutive hyphens, possibly by using a regex that replaces
one or more whitespace characters with a single hyphen.
export function calculateSum(numbers: number[]): number { | ||
return numbers.reduce((acc, num) => acc + num, 0); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add input validation for robustness.
While the logic is correct, the function should handle edge cases like null/undefined input arrays.
export function calculateSum(numbers: number[]): number {
+ if (!numbers || !Array.isArray(numbers)) {
+ return 0;
+ }
return numbers.reduce((acc, num) => acc + num, 0);
}
📝 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 function calculateSum(numbers: number[]): number { | |
return numbers.reduce((acc, num) => acc + num, 0); | |
} | |
export function calculateSum(numbers: number[]): number { | |
if (!numbers || !Array.isArray(numbers)) { | |
return 0; | |
} | |
return numbers.reduce((acc, num) => acc + num, 0); | |
} |
🤖 Prompt for AI Agents
In helper.ts around lines 5 to 7, the calculateSum function lacks input
validation for null or undefined arrays. Add a check at the start of the
function to verify that the input is a valid array; if not, return 0 or handle
the case appropriately to prevent runtime errors. This will make the function
more robust against invalid inputs.
export function isValidEmail(email: string): boolean { | ||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; | ||
return emailRegex.test(email); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Email regex is overly simplistic and lacks input validation.
The current regex pattern is too basic and will reject many valid email addresses. It also lacks input validation.
Consider using a more comprehensive approach:
export function isValidEmail(email: string): boolean {
+ if (!email || typeof email !== 'string') {
+ return false;
+ }
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+ // More comprehensive email regex
+ const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return emailRegex.test(email);
}
Alternatively, consider using a dedicated email validation library for production use.
📝 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 function isValidEmail(email: string): boolean { | |
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; | |
return emailRegex.test(email); | |
} | |
export function isValidEmail(email: string): boolean { | |
if (!email || typeof email !== 'string') { | |
return false; | |
} | |
// More comprehensive email regex | |
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; | |
return emailRegex.test(email); | |
} |
🤖 Prompt for AI Agents
In helper.ts around lines 9 to 12, the current email validation regex is too
simplistic and does not cover many valid email formats, nor does it validate
input thoroughly. Replace the regex with a more comprehensive pattern that
better matches the official email format specifications or integrate a
well-maintained email validation library to handle edge cases and improve
accuracy. Also, add input validation to ensure the email parameter is a
non-empty string before testing it.
export function debounce<T extends (...args: any[]) => any>( | ||
func: T, | ||
delay: number | ||
): (...args: Parameters<T>) => void { | ||
let timeoutId: NodeJS.Timeout; | ||
return (...args: Parameters<T>) => { | ||
clearTimeout(timeoutId); | ||
timeoutId = setTimeout(() => func(...args), delay); | ||
}; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix timeout type and initialization issues.
The function has environment compatibility and type issues that need addressing.
export function debounce<T extends (...args: any[]) => any>(
func: T,
delay: number
-): (...args: Parameters<T>) => void {
- let timeoutId: NodeJS.Timeout;
+): (...args: Parameters<T>) => void {
+ let timeoutId: number | NodeJS.Timeout | undefined;
return (...args: Parameters<T>) => {
- clearTimeout(timeoutId);
+ if (timeoutId) {
+ clearTimeout(timeoutId as any);
+ }
timeoutId = setTimeout(() => func(...args), delay);
};
}
Consider also preserving the original function's return type:
-): (...args: Parameters<T>) => void {
+): (...args: Parameters<T>) => ReturnType<T> | undefined {
📝 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 function debounce<T extends (...args: any[]) => any>( | |
func: T, | |
delay: number | |
): (...args: Parameters<T>) => void { | |
let timeoutId: NodeJS.Timeout; | |
return (...args: Parameters<T>) => { | |
clearTimeout(timeoutId); | |
timeoutId = setTimeout(() => func(...args), delay); | |
}; | |
} | |
export function debounce<T extends (...args: any[]) => any>( | |
func: T, | |
delay: number | |
): (...args: Parameters<T>) => ReturnType<T> | undefined { | |
let timeoutId: number | NodeJS.Timeout | undefined; | |
return (...args: Parameters<T>) => { | |
if (timeoutId) { | |
clearTimeout(timeoutId as any); | |
} | |
timeoutId = setTimeout(() => func(...args), delay); | |
}; | |
} |
🤖 Prompt for AI Agents
In helper.ts around lines 14 to 23, the debounce function uses NodeJS.Timeout
type which may cause compatibility issues in non-Node environments and timeoutId
is not initialized. Change the timeoutId type to ReturnType<typeof setTimeout>
for broader compatibility and initialize timeoutId properly. Also, update the
returned function to preserve the original function's return type by returning
the result of func calls correctly.
export function chunk<T>(array: T[], size: number): T[][] { | ||
const chunks: T[][] = []; | ||
for (let i = 0; i < array.length; i += size) { | ||
chunks.push(array.slice(i, i + size)); | ||
} | ||
return chunks; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add critical input validation to prevent infinite loops.
The function lacks validation for the size
parameter, which could cause infinite loops or unexpected behavior.
export function chunk<T>(array: T[], size: number): T[][] {
+ if (!array || !Array.isArray(array)) {
+ return [];
+ }
+ if (size <= 0 || !Number.isInteger(size)) {
+ throw new Error('Size must be a positive integer');
+ }
const chunks: T[][] = [];
for (let i = 0; i < array.length; i += size) {
chunks.push(array.slice(i, i + size));
}
return chunks;
}
📝 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 function chunk<T>(array: T[], size: number): T[][] { | |
const chunks: T[][] = []; | |
for (let i = 0; i < array.length; i += size) { | |
chunks.push(array.slice(i, i + size)); | |
} | |
return chunks; | |
} | |
export function chunk<T>(array: T[], size: number): T[][] { | |
if (!array || !Array.isArray(array)) { | |
return []; | |
} | |
if (size <= 0 || !Number.isInteger(size)) { | |
throw new Error('Size must be a positive integer'); | |
} | |
const chunks: T[][] = []; | |
for (let i = 0; i < array.length; i += size) { | |
chunks.push(array.slice(i, i + size)); | |
} | |
return chunks; | |
} |
🤖 Prompt for AI Agents
In helper.ts around lines 25 to 31, the chunk function does not validate the
size parameter, which can lead to infinite loops or unexpected behavior if size
is zero or negative. Add input validation at the start of the function to check
if size is a positive integer greater than zero, and throw an error or return an
empty array if the validation fails to prevent infinite loops.
Summary by CodeRabbit