Problem
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
Solution
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
```