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:
let 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:
let 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:
let path = 'img.png';
let ext = path.slice(-4);
if (ext === '.png' || ext === '.jpg') {
console.log('+++');
} else {
console.log('---');
}
Optimize the code below:
let num = 123;
if (String(num)[0] === '1' || String(num)[0] === '2') {
console.log('+++');
} else {
console.log('---');
}
Optimize the code below:
let date = new Date();
if (date.getDay() === 0 || date.getDay() === 6) {
console.log('weekend');
} else {
console.log('weekday');
}
Optimize the code below:
let 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)