Optimization of repetitive operations in JavaScript
Often, novice programmers thoughtlessly call the same function several times, wasting resources.
Let's look at an example. Let's say we have a string containing some path:
javascriptlet path = 'img.png';
Suppose we are faced with the task of
checking whether the path ends with
the extension .png or
.jpg. Some novice programmer
wrote the following code:
javascriptlet path = 'img.png';
if (path.slice(-4) === '.png' || path.slice(-4) === '.jpg') {
console.log('+++');
} else {
console.log('---');
}
What is wrong with this solution? The
problem is that the slice method
is called twice, doing the same
thing. This is, of course, not optimal.
To optimize, you need to slice the string once, write the result into a variable, and then use this variable further:
javascriptlet path = 'img.png';
let ext = path.slice(-4);
if (ext === '.png' || ext === '.jpg') {
console.log('+++');
} else {
console.log('---');
}
Задание 1
Optimize the code below:
javascriptlet num = 123;
if (String(num)[0] === '1' || String(num)[0] === '2') {
console.log('+++');
} else {
console.log('---');
}
Задание 2
Optimize the code below:
javascriptlet date = new Date();
if (date.getDay() === 0 || date.getDay() === 6) {
console.log('weekend');
} else {
console.log('weekday');
}
Задание 3
Optimize the code below:
javascriptlet date = new Date();
let res;
if (date.getFullYear() >= 2020 && date.getFullYear() <= 2030) {
res = date.getFullYear() + ' fits';
} else {
res = date.getFullYear() + ' doesn't fit';
}
console.log(res)