The task
You are given two non-empty arrays representing two non-negative integers. The digits are stored in reverse order and each of their items contain a single digit. Add the two numbers and return it as an array.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example: Input: [2,4,3] + [5,6,4] Output: [7,0,8]
const a1 = [2,4,3];
const a2 = [5,6,4];
My imperative solution
function addTwoNumbers(a1, a2) {
const len = a1.length > a2.length ? a1.length : a2.length;
const res = [];
let memo = 0;
const sanitize = n => n ? n : 0;
for (let i = 0; i < len; i++) {
let sum = sanitize(a1[i]) + sanitize(a2[i]) + memo;
memo = sum > 9 ? sum % 9 : 0;
sum = sum > 9 ? sum % 10 : sum;
res.push(sum);
}
return res;
}
console.log(addTwoNumbers(a1, a2));
My functional solution
const range = num => Array.from(new Array(num), (_, i) => i);
const addTwoNumbers2 = (a1, a2) => {
const sanitize = n => n ? n : 0;
const len = a1.length > a2.length ? a1.length : a2.length;
const {res} = range(len)
.reduce((acc,i) => {
let sum = sanitize(a1[i]) + sanitize(a2[i]) + acc.memo;
acc.memo = sum > 9 ? sum % 9 : 0;
sum = sum > 9 ? sum % 10 : sum;
acc.res.push(sum);
return acc;
}, {res: [], memo: 0,});
return res;
};
console.log(addTwoNumbers2(a1, a2));