JSFiddle - React, Tailwind, and code Playground
by sym3tri
HTML
<div id="output">
</div>
JavaScript
// get the rest of the number string exluding the last digit
function rest(s) {
if (s && s.length <= 1) {
return "";
}
return s.slice(0, s.length-1);
}
// gets the last digit from the number string
function getLastDigit(s) {
if (!s.length) {
return 0;
}
return parseInt(s[s.length-1], 10);
}
// main function
function add(a, b) {
var sumStr;
sumStr = (getLastDigit(a) + getLastDigit(b)).toString();
if (a.length === 1) {
return sumStr;
}
if (sumStr.length === 1) {
return add( rest(a), rest(b) ) + sumStr;
}
return add( add( rest(a), rest(b) ), sumStr[0]) + sumStr[1];
}
function print(msg) {
document.getElementById('output').innerHTML += msg + '<br/>';
}
print(add("8", "1"));
print(add("27", "78"));
print(add("10", "11"));
print(add("190", "10"));
print(add("999", "1"));