This is the "classic" algorithm for calculating the sum of digits uses the modulo-operator together with the division-operator. I had the idea of using the slice-method with a negative index for accomplishing the task.
/**
* Calculates sum of digits from a given number.
* @param { number } num
* @return { number }
* @throws { exception } Throws exception in
* case given parameter is not a number.
* Usage example:
* var CheckSum = calcCheckSum(328); // Returns 13
*/
function calcCheckSum(num) {
var ret = 0;
var i;
if (typeof num != 'number' || isNaN(num)) {
throw new Error('Number expected. { ' +
typeof num + ' } ' +
num + ' found.');
}
num = num.toString();
for (i = num.length; i > 0; i--) {
ret += parseInt(num.slice(i - 1, i));
}
return ret;
}
// -- TESTS -----------
for (var i = 0; i < 10; i++) {
var randomNumber =
Math.floor(
Math.random() * (100000 - 100)
) + 100;
var spacer = new Array(6);
spacer = spacer.join(' ');
console.log('%s : %s => %s',
('0' + i).slice(-2),
(spacer + randomNumber).slice(-5),
calcCheckSum(randomNumber)
);
}
try {
console.log(calcCheckSum('abcdef'));
} catch (e) {
console.error(e);
}
try {
console.log(calcCheckSum(NaN));
} catch (e) {
console.error(e);
}
// ------------------------------
It seems to work as expected. Nevertheless I would appreciate your opinions: shall I stay with the well-known algorithm or I can use my self-figured out solution?
Moreover, is my parameter validation and my documentation done well? Or do I have to improve something?