Skip to content

Conversation

alphamyd
Copy link
Contributor

This PR improves the existing factorial(n) function by adding input validation for negative numbers. Previously, calling factorial(-1) or any negative input would cause infinite recursion, eventually leading to a stack overflow. With this update, a RangeError is thrown when a negative number is passed.

Why this change is important:

  • Correctness: Mathematically, factorial is not defined for negative numbers.
  • Robustness: Prevents infinite recursion and potential stack overflow on invalid input.
  • Interview relevance: Input validation is a common area of oversight in candidate solutions. This change aligns the function with real-world expectations.
  • Clarity and semantics: Using RangeError instead of a generic Error makes it immediately clear that the issue is with the range of acceptable values, not a syntax issue or unexpected type. According to MDN, RangeError is appropriate when a value is not within the set or range of allowed values — which fits this case perfectly.
factorial(-5); // throws RangeError: Factorial is not defined for negative numbers
factorial(5);  // returns 120

The updated function stays concise and educational while being safer and more professional.

@alphamyd
Copy link
Contributor Author

I also updated the base case to handle both 0 and 1 directly, which avoids an unnecessary recursive call when n === 1. It’s a small optimization, but it keeps the call stack cleaner and better matches the mathematical definition.

@alphamyd
Copy link
Contributor Author

alphamyd commented Jun 3, 2025

@AllThingsSmitty wdyt?

Copy link
Owner

@AllThingsSmitty AllThingsSmitty left a comment

Choose a reason for hiding this comment

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

Ship it

@AllThingsSmitty AllThingsSmitty merged commit 5465fa0 into AllThingsSmitty:main Jun 3, 2025
@AllThingsSmitty AllThingsSmitty self-assigned this Jun 3, 2025
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.

2 participants