Skip to content

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

Closed
wants to merge 1 commit into from
Closed

Add helper.ts #69

wants to merge 1 commit into from

Conversation

averyjennings
Copy link

@averyjennings averyjennings commented Jul 30, 2025

Summary by CodeRabbit

  • New Features
    • Introduced new utility functions for string formatting, array chunking, summing numbers, email validation, and debouncing actions. These tools enhance data handling and user input processing throughout the application.

Copy link

coderabbitai bot commented Jul 30, 2025

Walkthrough

A 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

Cohort / File(s) Change Summary
New Utility Functions
helper.ts
Introduced five exported utility functions: formatString, calculateSum, isValidEmail, debounce, and chunk. Each addresses a distinct utility: string manipulation, array summation, email format validation, function debouncing, and array chunking.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Poem

In the warren of code, new helpers appear,
For strings and sums, and emails to clear.
Debounce a hop, chunk carrots with glee,
Five clever tricks for a rabbit like me!
🐇✨

Pre-Merge Checks (3 warnings)

❌ Failed Checks (3 warnings)
Check Name Status Explanation Resolution
Title Check ⚠️ Warning The pull request title 'Add helper.ts' is too generic and does not convey the specific utility functions introduced. Revise the title to clearly reflect the changes, e.g., 'Add helper module with formatString, calculateSum, isValidEmail, debounce, and chunk functions'.
Description Check ⚠️ Warning The pull request description is empty and lacks context, details, and rationale for the changes. Provide a detailed description explaining the purpose of the helper module, summaries of each function, usage examples, and testing notes, and consider adding a pull request template to the repository for consistency.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch featureBranch

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need 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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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.

Actionable comments posted: 5

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ef04b8d and 02245f3.

📒 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)

Comment on lines +1 to +3
export function formatString(input: string): string {
return input.trim().toLowerCase().replace(/\s+/g, '-');
}
Copy link

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.

Suggested change
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.

Comment on lines +5 to +7
export function calculateSum(numbers: number[]): number {
return numbers.reduce((acc, num) => acc + num, 0);
}
Copy link

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.

Suggested change
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.

Comment on lines +9 to +12
export function isValidEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
Copy link

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.

Suggested change
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.

Comment on lines +14 to +23
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);
};
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

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.

Suggested change
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.

Comment on lines +25 to +31
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;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

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.

Suggested change
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant