In the previous lesson, repeated function calls actually take very little time, and our optimization will not save much. However, everything will be much worse if we call a "heavy" function several times, which is executed for quite a long time.
Let, for example, we have a function that finds divisors of a number:
function getDivisorsSum(num) {
let res = 0;
for (let i = 1; i <= num; i++) {
if (num % i === 0) {
res += i;
}
}
return res;
}
Obviously, this function is quite "heavy". So it would be a bad idea to write code like this:
let num = 123456;
if (getDivisorsSum(num) >= 10 && getDivisorsSum(num) <= 100) {
console.log('+++');
} else {
console.log('---');
}
It is better, of course, to perform the "heavy" operation once and write the result into a variable, and then use this variable in the right places:
let num = 123456;
let sum = getDivisorsSum(num);
if (sum >= 10 && sum <= 100) {
console.log('+++');
} else {
console.log('---');
}
Optimize the code below:
let num = 1233456789;
if (getSumSquare(num) >= 10 && getSumSquare(num) <= 100) {
console.log('+++');
} else {
console.log('---');
}
function getSumSquare(num) {
let digits = String(num).split('');
let sum = 0;
for (let digit of digits) {
sum += digit ** 2;
}
return sum;
}