Skip to content
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

Update server.js #161

Merged
merged 3 commits into from
Nov 18, 2024
Merged

Update server.js #161

merged 3 commits into from
Nov 18, 2024

Conversation

skanda890
Copy link
Owner

@skanda890 skanda890 commented Nov 18, 2024

Summary by Sourcery

Enhancements:

  • Simplify the regex patterns for mathematical expressions by removing unnecessary patterns and updating existing ones for better clarity and performance.

Summary by CodeRabbit

  • New Features

    • Updated regex patterns for improved parsing of mathematical expressions, including support for square roots and π.
    • Enhanced handling for large power calculations with simplified outputs for exponents over 100,000.
    • Introduced new regex patterns for factorial, permutations, combinations, logarithmic, and trigonometric calculations with clearer explanations.
  • Bug Fixes

    • Refined explanations for square root and factorial calculations for better clarity.
  • Chores

    • Improved organization of regex patterns for better maintainability.

Copy link

sourcery-ai bot commented Nov 18, 2024

Reviewer's Guide by Sourcery

This PR updates the calculator server's expression handling by simplifying and modernizing the mathematical operations supported. The changes focus on streamlining the regex patterns and calculation logic, removing some less commonly used operations while adding support for π (pi) calculations.

No diagrams generated as the changes look simple and do not need a visual representation.

File-Level Changes

Change Details Files
Simplified and updated regular expression patterns for mathematical operations
  • Changed square root syntax from 'squareroot' to '√' symbol
  • Removed separate square operation in favor of power operation
  • Added support for π (pi) symbol
  • Simplified assignment regex pattern
  • Removed regex patterns for permutations, combinations, logarithms, and trigonometric functions
math-calculator/server.js
Streamlined calculation handling logic
  • Simplified square root calculation explanation
  • Updated large number handling for factorials
  • Modified power operation handling for very large exponents
  • Added new π (pi) calculation support with Math.PI conversion
  • Removed complex mathematical operations (permutations, combinations, logarithms, trigonometry)
math-calculator/server.js

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time. You can also use
    this command to specify where the summary should be inserted.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

coderabbitai bot commented Nov 18, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes in this pull request primarily modify the handleCalculation function in math-calculator/server.js. Key updates include revised regex patterns for mathematical expressions, specifically for square roots, powers, and the introduction of a new pattern for π. The handling of assignment-like expressions has been updated, and explanation strings for square roots and factorials have been refined. Additionally, support for permutations, combinations, logarithmic, and trigonometric calculations has been retained but enhanced for clarity.

Changes

File Change Summary
math-calculator/server.js - Enhanced handleCalculation function.
- Updated regex for square root to accommodate both squareroot<number> and √<number>.
- Introduced new regex for π.
- Adjusted regex for assignment-like expressions.
- Streamlined logic for square root and factorial calculations.
- Clarified explanations for permutations, combinations, logarithmic, and trigonometric calculations.

Possibly related PRs

  • Update server.js #156: This PR also modifies the handleCalculation function in math-calculator/server.js, focusing on regex patterns and handling of mathematical operations, which directly relates to the changes made in the main PR.
  • Update server.js #161: Similar to the main PR, this PR updates the handleCalculation function in math-calculator/server.js, specifically addressing regex patterns for square roots and powers, indicating a strong connection to the changes made.

Suggested reviewers

  • sourcery-ai

Poem

In the land of math where numbers play,
A rabbit hops with joy today.
With roots and powers all refined,
New patterns found, old ones left behind.
Simplified paths for calculations bright,
Hooray for changes, all feels just right! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @skanda890 - I've reviewed your changes - here's some feedback:

Overall Comments:

  • This PR introduces several breaking changes by removing trigonometric, logarithmic, permutation, and combination functions, and changing the square root syntax. Please provide justification for these removals and include a changelog/migration guide for existing clients.
  • The new large number handling for power operations (base^exponent) is less accurate than the previous logarithm-based calculation. Consider keeping the original implementation for mathematical precision.
Here's what I looked at during the review
  • 🟡 General issues: 2 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines 70 to 72
if (exponent > 100000) {
solution = `1 followed by ${exponent} zeros`;
explanation = `${base}^${exponent} is extremely large and has ${exponent + 1} digits.`;
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): The calculation of digits for large powers is incorrect

The number of digits should be calculated as floor(exponent * log10(base)) + 1. The current implementation assumes base 10, which is incorrect for other bases.

const combinationRegex = /(\d+)C(\d+)/;
const logRegex = /log\((\d+)\)/;
const trigRegex = /(sin|cos|tan)\((\d+)\)/;
const sqrtRegex = /√(\d+)(\^(-?\d+))?/; // Match "√<number>" and optional "^exponent"
Copy link

Choose a reason for hiding this comment

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

suggestion: Square root syntax should support both '√' and 'sqrt' for better accessibility

Consider modifying the regex to accept both notations: /(√|sqrt)(\d+)(^(-?\d+))?/

Suggested change
const sqrtRegex = /(\d+)(\^(-?\d+))?/; // Match "√<number>" and optional "^exponent"
const sqrtRegex = /(√|sqrt)(\d+)(\^(-?\d+))?/;

math-calculator/server.js Fixed Show fixed Hide fixed
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: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2b4a878 and 9a4afa7.

📒 Files selected for processing (1)
  • math-calculator/server.js (3 hunks)
🧰 Additional context used
🪛 GitHub Check: CodeQL
math-calculator/server.js

[failure] 55-55: Polynomial regular expression used on uncontrolled data
This regular expression that depends on a user-provided value may run slow on strings with many repetitions of '9'.


[failure] 56-56: Polynomial regular expression used on uncontrolled data
This regular expression that depends on a user-provided value may run slow on strings with many repetitions of '9'.


[failure] 65-65: Polynomial regular expression used on uncontrolled data
This regular expression that depends on a user-provided value may run slow on strings with many repetitions of '9'.

🔇 Additional comments (1)
math-calculator/server.js (1)

29-33: ⚠️ Potential issue

Fix the invalid characters in assignmentRegex pattern

The assignmentRegex contains special characters '', which may be unintended and could cause regex matching errors or unexpected behavior. Replace '' with the correct characters or remove them if unnecessary.

Apply this diff to fix the regex pattern:

-  const assignmentRegex = /([^=]+)=([^=]+)\^([^=]+)/; // Match for assignment-like expressions (x=10)^999999
+  const assignmentRegex = /([^=]+)=([^=]+)\^([^=]+)/; // Match for assignment-like expressions (x=10)^999999

Likely invalid or redundant comment.

Comment on lines 29 to 31
const sqrtRegex = /√(\d+)(\^(-?\d+))?/; // Match "√<number>" and optional "^exponent"
const factorialRegex = /(\d+)!/; // Match "number!"
const largePowerRegex = /(\d+)\^(\d+)/; // Match "base^exponent"
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prevent potential ReDoS vulnerabilities in regular expressions

The current regular expressions may be susceptible to Regular Expression Denial of Service (ReDoS) attacks if supplied with malicious input. Consider limiting the length of the input or using safer regex patterns to prevent performance issues.

Apply this diff to limit the input length:

+ const MAX_INPUT_LENGTH = 1000; // Define a maximum acceptable input length

  function handleCalculation(expression) {
+   if (expression.length > MAX_INPUT_LENGTH) {
+     throw new Error('Input too long');
+   }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 49 to 54
const number = parseFloat(match[1]); // Extract the number after ""
const exponent = match[3] ? parseFloat(match[3]) : 1; // Default to 1 if no exponent is provided

// Calculate the square root and apply the exponent
const sqrtValue = Math.sqrt(number);
solution = Math.pow(sqrtValue, exponent); // Apply exponent to the square root

explanation = `The square root of ${number} is calculated as √${number}, which is ${sqrtValue}. Then raising this value to the power of ${exponent} gives ${solution}.`;
} else if (squareRegex.test(expression)) {
const number = parseFloat(expression.match(squareRegex)[1]);
solution = Math.pow(number, 2);
explanation = `The square of ${number} is ${solution}.`;
} else if (powerRegex.test(expression)) {
const match = expression.match(powerRegex);
const base = new Decimal(match[1]);
const exponent = new Decimal(match[2]);

if (exponent.gt(1000)) {
// Handle extremely large exponents
const digits = Math.floor(Math.log10(base.toNumber()) * exponent.toNumber()) + 1;
solution = `1 followed by ${digits - 1} zeros`;
explanation = `${base}^${exponent} is extremely large and has ${digits} digits.`;
} else {
solution = base.pow(exponent).toString();
explanation = `${base}^${exponent} = ${solution}.`;
}
const sqrtValue = Math.sqrt(number); // Calculate square root
solution = Math.pow(sqrtValue, exponent); // Apply exponent
explanation = `The square root of ${number} is √${number} = ${sqrtValue}. Then raising it to the power of ${exponent} gives ${solution}.`;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle negative numbers in square root calculations

The current implementation does not handle negative numbers. Calculating the square root of a negative number results in NaN, which may not be the intended behavior. Consider adding input validation to handle negative inputs appropriately.

Apply this diff to add input validation:

  const number = parseFloat(match[1]); // Extract the number after "√"
+ if (number < 0) {
+   throw new Error(`Cannot calculate the square root of a negative number: ${number}`);
+ }
  const exponent = match[3] ? parseFloat(match[3]) : 1; // Default to 1 if no exponent is provided
📝 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
const number = parseFloat(match[1]); // Extract the number after "√"
const exponent = match[3] ? parseFloat(match[3]) : 1; // Default to 1 if no exponent is provided
// Calculate the square root and apply the exponent
const sqrtValue = Math.sqrt(number);
solution = Math.pow(sqrtValue, exponent); // Apply exponent to the square root
explanation = `The square root of ${number} is calculated as √${number}, which is ${sqrtValue}. Then raising this value to the power of ${exponent} gives ${solution}.`;
} else if (squareRegex.test(expression)) {
const number = parseFloat(expression.match(squareRegex)[1]);
solution = Math.pow(number, 2);
explanation = `The square of ${number} is ${solution}.`;
} else if (powerRegex.test(expression)) {
const match = expression.match(powerRegex);
const base = new Decimal(match[1]);
const exponent = new Decimal(match[2]);
if (exponent.gt(1000)) {
// Handle extremely large exponents
const digits = Math.floor(Math.log10(base.toNumber()) * exponent.toNumber()) + 1;
solution = `1 followed by ${digits - 1} zeros`;
explanation = `${base}^${exponent} is extremely large and has ${digits} digits.`;
} else {
solution = base.pow(exponent).toString();
explanation = `${base}^${exponent} = ${solution}.`;
}
const sqrtValue = Math.sqrt(number); // Calculate square root
solution = Math.pow(sqrtValue, exponent); // Apply exponent
explanation = `The square root of ${number} is √${number} = ${sqrtValue}. Then raising it to the power of ${exponent} gives ${solution}.`;
const number = parseFloat(match[1]); // Extract the number after "√"
if (number < 0) {
throw new Error(`Cannot calculate the square root of a negative number: ${number}`);
}
const exponent = match[3] ? parseFloat(match[3]) : 1; // Default to 1 if no exponent is provided
const sqrtValue = Math.sqrt(number); // Calculate square root
solution = Math.pow(sqrtValue, exponent); // Apply exponent
explanation = `The square root of ${number} is √${number} = ${sqrtValue}. Then raising it to the power of ${exponent} gives ${solution}.`;

Comment on lines 65 to 75
} else if (largePowerRegex.test(expression)) {
const match = expression.match(largePowerRegex);
const base = parseInt(match[1], 10);
const exponent = parseInt(match[2], 10);

if (exponent > 100000) {
solution = `1 followed by ${exponent} zeros`;
explanation = `${base}^${exponent} is extremely large and has ${exponent + 1} digits.`;
} else {
solution = Math.pow(base, exponent);
explanation = `${base}^${exponent} = ${solution}.`;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid potential overflow and performance issues with large exponents

Calculating Math.pow(base, exponent) with very large exponents may cause performance issues or overflow errors. Consider adding a check to handle large exponents more efficiently or limit the allowable exponent value.

Apply this diff to adjust the exponent handling:

  const base = parseInt(match[1], 10);
  const exponent = parseInt(match[2], 10);

+ if (exponent > MAX_EXPONENT_VALUE) {
+   throw new Error(`Exponent ${exponent} is too large to compute safely.`);
+ }
  
  if (exponent > 100000) {
    solution = `1 followed by ${exponent} zeros`;
    explanation = `${base}^${exponent} is extremely large and has ${exponent + 1} digits.`;
  } else {
    solution = Math.pow(base, exponent);
    explanation = `${base}^${exponent} = ${solution}.`;
  }

Define MAX_EXPONENT_VALUE at the beginning of your file:

+ const MAX_EXPONENT_VALUE = 1000000; // Set an appropriate maximum exponent value

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 GitHub Check: CodeQL

[failure] 65-65: Polynomial regular expression used on uncontrolled data
This regular expression that depends on a user-provided value may run slow on strings with many repetitions of '9'.

const digits = Math.floor(Math.log10(base.toNumber()) * exponent.toNumber()) + 1;
solution = `1 followed by ${digits - 1} zeros`;
explanation = `${base}^${exponent} is extremely large and has ${digits} digits.`;
} else {
solution = base.pow(exponent).toString();
explanation = `${base}^${exponent} = ${solution}.`;
}
} else if (assignmentRegex.test(expression)) {

Check failure

Code scanning / CodeQL

Polynomial regular expression used on uncontrolled data High

This
regular expression
that depends on
a user-provided value
may run slow on strings starting with '\\ue001' and with many repetitions of '\\ue001<'.
const digits = Math.floor(Math.log10(base.toNumber()) * exponent.toNumber()) + 1;
solution = `1 followed by ${digits - 1} zeros`;
explanation = `${base}^${exponent} is extremely large and has ${digits} digits.`;
} else {
solution = base.pow(exponent).toString();
explanation = `${base}^${exponent} = ${solution}.`;
}
} else if (assignmentRegex.test(expression)) {
const match = expression.match(assignmentRegex);

Check failure

Code scanning / CodeQL

Polynomial regular expression used on uncontrolled data High

This
regular expression
that depends on
a user-provided value
may run slow on strings starting with '\\ue001' and with many repetitions of '\\ue001<'.
@skanda890 skanda890 merged commit f7908e9 into main Nov 18, 2024
8 of 17 checks passed
@skanda890 skanda890 deleted the skanda890-patch-1 branch November 18, 2024 09:51
Copy link

sonarcloud bot commented Nov 18, 2024

Quality Gate Failed Quality Gate failed

Failed conditions
5 Security Hotspots

See analysis details on SonarQube Cloud

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