JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" id="num" placeholder="Введите число">
<button>Узнать</button>
<h1>Результат</h1>
CSS
h1 {
padding: 3px;
border: 1px solid #ccc;
text-align: center;
}
JavaScript
// Сложение всех входящих в число цифр до тех пор, пока не останется одна цифра.
// course => Введение в программирование
// author => Roman Zharikov (zharikov.site)
//document.addEventListener("DOMContentLoaded", function() {
// define function
const check = (num) => (num.length > 1) ? 1 : 0;
const sum = (one, two) => parseInt(one) + parseInt(two);
const addDigits = (num) => {
let size = num.length;
if (check(num)) {
let j = 0,
res = 0;
while (j < size) {
if (j === 0) {
res += sum(num[size - ++j], num[size - ++j]);
if (isNaN(res))
return NaN;
if (check((res + '')))
res = addDigits((res + ''));
} else {
res = sum(res, num[size - ++j]);
if (check((res + '')))
res = addDigits((res + ''));
}
}
return res;
} else {
return parseInt(num);
}
}
var button = document.getElementsByTagName('button')[0],
out = document.getElementsByTagName('h1')[0],
num = document.getElementById('num');
button.addEventListener('click', function() {
// call function and out result to DOM element
out.innerHTML = addDigits(num.value);
});
//});