test

Benchmark created on


Setup

function add(str1: string, str2: string): string {
  if (!str1.length && !str2.length) return "0";

  const N = Math.max(str1.length, str2.length);
  str1 = str1.padStart(N, "0");
  str2 = str2.padStart(N, "0");

  const result = Array(N).fill("0");
  let carry = 0;

  for (const i of reverseIndex(N - 1, 0)) {
    const n1 = parseInt(str1[i], 10);
    const n2 = parseInt(str2[i], 10);
    const sum = n1 + n2 + carry;
    carry = Math.floor(sum / 10);
    result[i] = String(sum % 10);

    console.log(n1, n2, carry, result.join(""));
  }

  if (carry > 0) {
    result.unshift(String(carry));
  }

  return result.join("");
}

Test runner

Ready to run.

Testing in
TestOps/sec
t1
add("12", "34")
ready
t2
add("12", "34")
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.