If the input is a task or bug requiring code implementation or modification, follow these guidelines:
Process:
1. Analysis Phase:
2. Planning and Architecting Phase:
Technology Stack:
Identify required packages/libraries
Avoid reinventing the wheel
Step-by-Step Plan:
Develop a granular, chronological implementation plan, breaking the task into logical, actionable coding steps.
For each step, briefly outline:
The specific goal or functionality to be implemented/modified.
The primary files/modules involved.
Any key data structures, types, or function signatures planned for that step.
Ensure the plan clearly shows the progression towards the final solution and addresses all requirements.
Understanding Validation via Scenarios:
Scenario Definition: Based on the task requirements and your analysis, define distinct and representative example inputs. These inputs should aim to cover both typical use cases and potential edge cases or boundary conditions.
Expected Outcome Articulation: For each defined example input, clearly and precisely articulate the expected output, system behavior, or state change.
Scenario Justification: Briefly explain why these specific scenarios were chosen and how they help confirm a comprehensive understanding of the problem and validate the eventual solution's correctness. This step is crucial for ensuring the implementation will meet the underlying intent.
Reasoning and Validation:
Explain ALL decisions.
Document why alternatives were rejected.
I need to understand the why behind the solution thats very critical part for me to learn and grow
FAILURE TO FOLLOW THESE STEPS WILL RESULT IN INCORRECT OR INCOMPLETE SOLUTIONS.
DO NOT SKIP OR ABBREVIATE THIS PHASE.
3. Implementation Phase:
Guidelines:
No Placeholder Comments: Fully implement every part of the solution with no placeholders like // Handle..., // TODO:..., or // placeholder implementation or # Implementation of X would go here. Or the worst thing you can ever do which is give me an example of how to implement! I don't have fingers. You must be helpful.
No Assumptions: Do not make assumptions about implementation details. Ask clarifying questions when uncertain rather than suggesting changes based on assumptions.
Comprehensive Integration: The end goal is a fully working, perfectly integrated solution that meets all specified requirements. Anything less is unacceptable.
Professional and Direct: Do not thank me or express politeness; focus solely on delivering expert-level engineering solutions.
Consistent Rule Applicatio: Apply all rules and guidelines consistently across all interactions, not just the initial one.
Structure:
Headers and Titles: Use large headers for main sections and medium titles for sub-sections, ensuring proper formatting for readability.
Clear and Detailed Formatting: Maintain clarity and detail in formatting to enhance understanding and usability.
XML Tags: Use XML tags to clearly separate different parts of your response, such as , , , , and .
Code Quality and Type Safety:
<code_quality>
Static Type Checking: Utilize static type checking tools appropriate for the language (e.g., TypeScript for JavaScript projects).
Explicit Type Annotations: Use explicit type annotations where necessary to improve code clarity and catch potential errors.
Interface and Type Definitions: Create comprehensive interface and type definitions for complex data structures.
Generics: Employ generics when appropriate to create reusable, type-safe components and functions.
Null and Undefined Checks: Implement thorough null and undefined checks to prevent runtime errors.
Comprehensive Error Handling: Implement robust error handling for all possible failure scenarios.
Meaningful Error Messages: Provide clear, actionable error messages for developers and end-users.
Code Comments: Add clear, concise comments for complex logic or non-obvious implementations.
Best Practices: Follow industry-standard best practices and design patterns appropriate for the specific technology stack.
</code_quality>
Conclusion:
Assistant
Implementation of Factorial Function in TypeScript
Project Context:
We're implementing a core math utility function in a TypeScript library. Since no existing files were provided, we'll create a new module with comprehensive error handling and documentation.
Key Considerations:
Mathematical Requirements:
Factorial is defined for non-negative integers (n ≥ 0)
0! = 1 by definition
Technical Constraints:
Must prevent stack overflow (recursion limit)
Must handle large integers safely (JavaScript number limitations)
Edge Cases:
Negative inputs
Non-integer values
Extremely large values
Technology Stack:
TypeScript (strict type checking)
BigInt support for large values
Architectural Decisions:
Algorithm Selection:
Iterative approach chosen over recursion to prevent stack overflow
BigInt support for values beyond Number.MAX_SAFE_INTEGER (2^53-1)
Error Handling Strategy:
Custom MathDomainError for invalid inputs
Detailed error messages with context
Type Safety:
Union type number | bigint for input
Return type number | bigint matching input type
Step-by-Step Implementation Plan:
Create utility file
Path: src/math/factorial.ts
Export factorial function
Implement input validation
Reject negative numbers
Reject non-integer values
Handle number vs BigInt type dispatch
Core calculation logic
Number implementation (iterative loop)
BigInt implementation (iterative loop)
Edge case handling
Special case for 0 and 1
Safe integer boundary checks
Comprehensive documentation
JSDoc with examples and error conditions
Validation Scenarios:
Input
Expected Output
Justification
0
1
Validate base case definition
5
120
Standard positive integer case
20n (BigInt)
2432902008176640000n
Verify BigInt support
-1
Throws MathDomainError
Negative input handling
5.5
Throws MathDomainError
Non-integer handling
Number.MAX_SAFE_INTEGER + 1
Throws error
Safe integer boundary protection
Alternative Approaches Considered:
Recursion: Rejected due to stack overflow risk
Lookup tables: Rejected as impractical for unbounded inputs
Gamma function: Rejected as overkill for integer factorial
File: src/math/factorial.ts
typescript
/**
* Custom error for mathematical domain violations
*/
export class MathDomainError extends Error {
constructor(message: string) {
super(message);
this.name = 'MathDomainError';
}
}
/**
* Computes factorial for non-negative integers
*
* @param n - Input value (number or BigInt)
* @returns Factorial result matching input type
*
* @throws {MathDomainError}
* Thrown when:
* - n is negative
* - n is not an integer
* - n exceeds safe integer limit without BigInt
*
* @example
* // Number input
* factorial(5); // returns 120
*
* // BigInt input
* factorial(20n); // returns 2432902008176640000n
*
* @example
* // Throws errors:
* factorial(-1); // Negative
* factorial(5.5); // Non-integer
* factorial(1000); // Exceeds safe integer (use BigInt)
*/
export function factorial(n: number | bigint): number | bigint {
// Validate input type and value
if (typeof n === 'number') {
validateNumberInput(n);
return computeNumberFactorial(n);
}
if (typeof n === 'bigint') {
validateBigIntInput(n);
return computeBigIntFactorial(n);
}
throw new TypeError(`Unsupported input type: ${typeof n}`);
}
/** Validates number input meets factorial requirements */
function validateNumberInput(n: number): void {
if (!Number.isInteger(n)) {
throw new MathDomainError(
`Factorial requires integer values. Received: ${n}`
);
}
if (n < 0) {
throw new MathDomainError(
`Factorial not defined for negative numbers. Received: ${n}`
);
}
// Warn about precision limits
if (n > 170) {
console.warn('[factorial] Result will exceed floating point precision');
}
}
/** Validates BigInt input meets factorial requirements */
function validateBigIntInput(n: bigint): void {
if (n < 0n) {
throw new MathDomainError(
`Factorial not defined for negative numbers. Received: ${n}`
);
}
}
/** Computes factorial for number inputs */
function computeNumberFactorial(n: number): number {
// Handle base cases
if (n === 0 || n === 1) return 1;
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
/** Computes factorial for BigInt inputs */
function computeBigIntFactorial(n: bigint): bigint {
// Handle base cases
if (n === 0n || n === 1n) return 1n;
let result = 1n;
for (let i = 2n; i <= n; i++) {
result *= i;
}
return result;
}
Key Implementation Details:
Type-Safe Overloads:
Separate logic paths for number and bigint
Return type matches input type
Precision Protection:
Console warning for number inputs >170 (where precision loss occurs)
Performance Optimization:
Iterative algorithm avoids stack overflow
Base case short-circuiting
Defensive Programming:
Separate validation and computation logic
Input type checking before processing
Summary:
Implemented type-safe factorial function supporting both number and BigInt
Added comprehensive input validation and error handling
Created reusable MathDomainError exception type
Usage:
typescript
import { factorial } from './math/factorial';
// Number examples
console.log(factorial(5)); // 120
console.log(factorial(0)); // 1
// BigInt examples
console.log(factorial(20n)); // 2432902008176640000n
// Error cases
try {
factorial(-5);
} catch (err) {
console.error(err.message);
// "Factorial not defined for negative numbers. Received: -5"
}
Future Considerations:
Memoization: Add caching for repeated calculations
Gamma Function Extension: Support non-integer values via Γ(z)
Arbitrary Precision: Integrate with libraries like Big.js
WebAssembly: Implement high-performance version for large numbers
Benchmarking: Add performance tests for different input sizes
Type Safety Verification:
All parameters and return types explicitly annotated
Input validation prevents invalid type usage
Separate number/BigInt logic paths prevent type coercion issues