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

AI solution for JavaScript Coding Question on BFE.dev
114. implement BigInt multiplication

One possible solution is to use the "long multiplication" algorithm that we typically use by hand. We can start with the last digit of the second number and multiply it with each digit of the first number, adding the resulting product to the corresponding position of the result. We then move on to the second-last digit of the second number and repeat the process, but shifting the result to the left by one position each time. Finally, we add up all the partial results to obtain the final answer.

Here is the code:

function multiply(a, b) {
  const sign = (a.charAt(0) === '-' ? -1 : 1) * (b.charAt(0) === '-' ? -1 : 1); // determine sign
  a = a.replace(/-/g, ''); // remove sign
  b = b.replace(/-/g, '');

  const result = [];
  for (let i = b.length - 1; i >= 0; i--) {
    let carry = 0;
    const partial = [];
    for (let j = a.length - 1; j >= 0; j--) {
      const product = (b.charAt(i) - '0') * (a.charAt(j) - '0') + carry;
      partial.unshift(product % 10);
      carry = Math.floor(product / 10);
    }
    if (carry > 0) {
      partial.unshift(carry);
    }
    for (let k = 0; k < (b.length - 1 - i); k++) {
      partial.push(0);
    }
    result.push(partial);
  }

  let finalResult = '';
  let carry = 0;
  for (let i = 0; i < result[result.length - 1].length; i++) {
    let sum = carry;
    for (let j = 0; j < result.length; j++) {
      if (i < result[j].length) {
        sum += result[j][i];
      }
    }
    finalResult = (sum % 10) + finalResult;
    carry = Math.floor(sum / 10);
  }
  if (carry > 0) {
    finalResult = carry + finalResult;
  }
  return (sign === -1 ? '-' : '') + finalResult;
}

Note that we first determine the sign of the result by multiplying the signs of the input numbers. We then remove the minus signs and store them temporarily, and perform the long multiplication as described above. Finally, we add back the minus sign if necessary and return the result as a string.

Here are some test cases:

console.log(multiply('1123456787654323456789', '1234567887654323456')); // '1386983673205309924427166592431045142784'
console.log(multiply('1123456787654323456789', '-1234567887654323456')); // '-1386983673205309924427166592431045142784'
console.log(multiply('-1123456787654323456789', '1234567887654323456')); // '-1386983673205309924427166592431045142784'
console.log(multiply('-1123456787654323456789', '-1234567887654323456')); // '1386983673205309924427166592431045142784'