function add (a, b) {
var res = '', c = 0
a = a.split('')
b = b.split('')
while (a.length || b.length || c) {
c += ~~a.pop() + ~~b.pop()
res = c % 10 + res
c = c > 9
}
return res
}
add('63829983432984289347293874', '90938498237058927340892374089')
function add(a, b) {
let result = '';
let remain = 0;
if (b.length > a.length) {
[a, b] = [b, a];
}
b = [b];
for (let i = a.length - 1; i >= 0; --i) {
const n1 = Number(a[i]);
const n2 = Number(b.pop() ?? 0);
let sum = n1 + n2 + remain;
if (sum > 9) {
let temp = sum;
sum %= 10;
remain = (temp - sum) / 10;
} else {
remain = 0;
}
result = sum + result;
}
if (remain) {
result = remain + result;
}
return result;
}
add('63829983432984289347293874', '90938498237058927340892374089')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
kata solution 1 | |
my solution |
Test name | Executions per second |
---|---|
kata solution 1 | 1969907.8 Ops/sec |
my solution | 253834.6 Ops/sec |
Overview of the Benchmark
The provided JSON represents a JavaScript benchmark, specifically designed to compare the performance of two different approaches for adding two large strings.
Benchmark Definition
The Benchmark Definition
section provides a brief description of the test case. In this case, it's empty ("Description": null
). The Script Preparation Code
and Html Preparation Code
fields are also empty, indicating that no special setup or HTML is required to run the benchmark.
Individual Test Cases
There are two test cases:
function add(a, b) {
var res = '';
a = a.split('');
b = b.split('');
while (a.length || b.length || c) {
c += ~~a.pop() + ~~b.pop();
res = c % 10 + res;
c = c > 9;
}
return res;
}
function add(a, b) {
let result = '';
let remain = 0;
if (b.length > a.length) {
[a, b] = [b, a];
}
b = [...b];
for (let i = a.length - 1; i >= 0; --i) {
const n1 = Number(a[i]);
const n2 = Number(b.pop() ?? 0);
let sum = n1 + n2 + remain;
if (sum > 9) {
let temp = sum;
sum %= 10;
remain = (temp - sum) / 10;
} else {
remain = 0;
}
result = sum + result;
}
if (remain) {
result = remain + result;
}
return result;
}
Comparison of Approaches
The two implementations differ in their use of iteration and handling of overflow:
Pros and Cons
Library and Special Features
There are no libraries mentioned in the benchmark code. However, both implementations utilize JavaScript features such as:
Other Alternatives
Some possible alternatives for implementing this benchmark include:
Note that these alternatives may not be relevant or feasible depending on the specific requirements and constraints of the benchmark.