4
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ split your string using the delimiter / then check the index 0 and the index 2? \$\endgroup\$
    – IEatBagels
    Oct 22, 2019 at 13:41

1 Answer 1

4
\$\begingroup\$

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

```
\$\endgroup\$
2
  • \$\begingroup\$ Wouldn't this return true for eenfinancieelramp#onwilligeklantenkaartoon? (How do I check lazy evaluation?) \$\endgroup\$
    – greybeard
    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 is a, is evaluated to false then whole expression is false and there is no need to evaluate b \$\endgroup\$
    – purple
    Nov 2, 2019 at 8:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.