I have a string, for example: dashboard/12398911/overzicht
and I want to check that string for 2 values. For dashboard
and overzicht
. If the first check is false, then the second check doesn't need to happen.
This is my current code:
private pageTypes = ['dashboard', 'klantenkaart', 'complexkaart', 'objectkaart', 'collegakaart'];
private subTypes = ['overzicht', 'tijdlijn', 'contracten', 'financieel', 'mededelingen'];
private isOnPageWithFilter(currentUrl: string): boolean {
for (const pageType of this.pageTypes) {
if (currentUrl.includes(pageType)) {
for (const subType of this.subTypes) {
if (currentUrl.includes(subType)) {
return true;
}
}
}
}
return false;
}
I was wondering if there's a way of doing this where I don't need a nested for loop.
Plunkr: https://plnkr.co/edit/FXhbCr9aaXcL61g3q7Fe?p=preview
1 Answer 1
You can simplify it by using Array.prototype.some method and lazy evaluation of &&
operator
const pageTypes = ['dashboard', 'klantenkaart', 'complexkaart', 'objectkaart', 'collegakaart'];
const subTypes = ['overzicht', 'tijdlijn', 'contracten', 'financieel', 'mededelingen'];
function isOnPageWithFilter(currentUrl) {
return pageTypes.some(x => currentUrl.includes(x)) && subTypes.some(x => currentUrl.includes(x));
}
console.log(isOnPageWithFilter('foobar.com?dashboard')); // false
console.log(isOnPageWithFilter('foobar.com?dashboard&overzicht')); // true
```
-
\$\begingroup\$ Wouldn't this return
true
foreenfinancieelramp#onwilligeklantenkaartoon
? (How do I check lazy evaluation?) \$\endgroup\$greybeard– greybeard2019年11月01日 07:02:47 +00:00Commented Nov 1, 2019 at 7:02 -
\$\begingroup\$ In JavaScript (and many other languages) logical operators (&&,||) are evaluated lazily. This means that if first part of expression
a && b
, that isa
, is evaluated to false then whole expression is false and there is no need to evaluateb
\$\endgroup\$purple– purple2019年11月02日 08:40:17 +00:00Commented Nov 2, 2019 at 8:40
/
then check the index 0 and the index 2? \$\endgroup\$