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

AI solution for JavaScript Coding Question on BFE.dev
109. implement `Math.pow()`

Here's one possible solution to implement Math.pow():

function pow(base, exponent) {
  if (exponent === 0) {
    return 1;
  } else if (exponent < 0) {
    return 1 / pow(base, -exponent);
  } else {
    return base * pow(base, exponent - 1);
  }
}

This solution uses recursion to recursively multiply the base by itself until the exponent is reduced to 0. If the exponent is negative, it instead negates the exponent and takes the reciprocal of the result of a recursive call. This implementation only works for integer exponents.

To address the follow-up question about a faster solution, we can use the fact that a^n can be computed as (a^2)^(n/2) if n is even, and as a*(a^(n-1)) if n is odd. This means we can repeatedly square the base and divide the exponent by 2 until the exponent is reduced to 0. Here's the updated implementation using this approach:

function pow(base, exponent) {
  if (exponent === 0) {
    return 1;
  } else if (exponent < 0) {
    return 1 / pow(base, -exponent);
  } else {
    let result = 1;
    while (exponent > 0) {
      if (exponent % 2 === 1) {
        result *= base;
      }
      base *= base;
      exponent = Math.floor(exponent / 2);
    }
    return result;
  }
}

This implementation is much faster for large exponents, as we only need to perform logarithmically many multiplications instead of linearly many.