This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for JavaScript Coding Question on BFE.dev
93. Generate Fibonacci Number with recursion

One approach to optimize the recursive function is to use memoization. This means that we store the result of each Fibonacci number calculated so far and reuse it if it has already been computed.

Here's how we can implement it in JavaScript:

const memo = {};

const fib = (n) => {
  if (n === 0) return 0;
  if (n === 1) return 1;

  if (memo[n]) return memo[n]; // if result already exists in memo, return it

  memo[n] = fib(n - 1) + fib(n - 2); // store result in memo for future use
  return memo[n];
}

console.log(fib(10)); // 55
console.log(fib(1000)); // 4.346655768693743e+208

By using memoization, we can now compute the 1000th Fibonacci number without causing a stack overflow or freezing the browser.