Autumn Sale50% off with code BOOSTAI
ChatGPT Prompt Template

TypeScript Fibonacci Function

A prompt to generate an efficient TypeScript function for calculating the Fibonacci sequence with detailed comments.

ChatGPTCategory: Programming & Code

Prompt Template

You are an expert TypeScript developer.
I need a TypeScript function that efficiently calculates the Fibonacci sequence. Please ensure the function is optimized for performance and includes detailed comments explaining each part of the code and the reasoning behind it. The comments should help a beginner understand how the function works and why it's written in a particular way.

Here are some additional requirements:
- The function should handle large input values efficiently.
- Avoid using recursion to prevent stack overflow issues.
- Make sure the code is clean and follows best practices.

Please write the function and include the comments as requested.
Tags:#typescript#fibonacci#function#efficient#code comments
Absolutely, here is an efficient TypeScript function to calculate the Fibonacci sequence with detailed comments:

```typescript
// Function to calculate the nth Fibonacci number
function fibonacci(n: number): number {
    // Check if the input is a valid non-negative integer
    if (n < 0) {
        throw new Error("Input must be a non-negative integer.");
    }

    // Base cases: 0th and 1st Fibonacci numbers
    if (n === 0) return 0;
    if (n === 1) return 1;

    // Variables to store the previous two Fibonacci numbers
    let prev = 0;
    let curr = 1;

    // Loop to calculate the nth Fibonacci number
    for (let i = 2; i <= n; i++) {
        // Calculate the next Fibonacci number
        const next = prev + curr;
        // Update the previous two Fibonacci numbers
        prev = curr;
        curr = next;
    }

    // Return the nth Fibonacci number
    return curr;
}

// Example usage:
console.log(fibonacci(10)); // Output: 55
```

Explanation of the code:
1. **Input Validation**: The function first checks if the input `n` is a non-negative integer. If not, it throws an error to ensure the function is used correctly.
2. **Base Cases**: If `n` is 0 or 1, the function returns 0 or 1 respectively, as these are the first two numbers in the Fibonacci sequence.
3. **Initialization**: Two variables, `prev` and `curr`, are initialized to store the previous two Fibonacci numbers. Initially, `prev` is set to 0 and `curr` to 1.
4. **Loop**: A `for` loop runs from 2 to `n`. In each iteration, it calculates the next Fibonacci number by adding the previous two numbers (`prev` and `curr`). The `prev` and `curr` variables are then updated for the next iteration.
5. **Return**: After the loop completes, the function returns `curr`, which now holds the nth Fibonacci number.

This approach ensures the function runs efficiently, even for large values of `n`, by using an iterative method instead of recursion, thereby avoiding potential stack overflow issues.
Save & Organize on iOS

Use this prompt on your iPhone & iPad

PromptKit keeps your 300+ favorite prompts ready at your fingertips with 1-click clipboard actions and offline private iCloud sync.