# Long arithmetic addition implemented in functional style

This implementation uses ECMA6 syntax and babel as transpiler. You can use this code to add integers which are bigger than Number.MAX_SAFE_INTEGER.

var _ = require('underscore'),
assert = require('assert');

var strAdd = function(lnum, rnum) {
var {rem, res} = _.chain(
_.zip(
lnum.split('').reverse(),
rnum.split('').reverse()
)
).reduce(
({rem, res}, [left, right]) => {
var sum = Number(left || 0) + Number(right || 0) + rem;
res.push(
sum % 10
);
return {
res,
rem: ~~(sum/ 10)
};
},
{
rem: 0,
res: []
}
).value();
if (rem !== 0) {
res.push(rem);
}
return res.reverse().join('');
};

• This is not Long arithmetic but Variable precision arithmetic!
– N74
Commented Nov 3, 2015 at 15:14
• That's much better. Commented Nov 3, 2015 at 16:23

### Input validation

The function will happily return non-sense result when an argument contains not only digits. Unless you are absolutely certain that this function is used in a safe context, it would be good to validate the inputs.

Going even further, I would create a validate function that returns a number or else throws an exception, and call it after splitting:

  lnum.split('').map(validate).reverse(),
rnum.split('').map(validate).reverse()


This way the summing step will not need anymore the Number conversions, a bit simpler:

  var sum = (left || 0) + (right || 0) + rem;


### Cleverness

I find this clever, but hacky:

rem: ~~(sum/ 10)


I suggest to just spell out the intention nicely:

rem: sum > 9 ? 1 : 0


On the other hand, instead of this:

if (rem !== 0) {


Since the value of rem is guaranteed to be either 0 or 1, I think it's totally fine to be lazy and rely on the truthiness:

if (rem) {