javascriptif-statementhigher-order-functionsor-operatoror-condition

Replacing "||" Conditionals in Javascript


Well, here goes my first stack overflow post!

Hello everyone, I have been learning a lot about functional programming recently. I found some older videos over at funfunfunction which whets my appetite and I've been playing around with them.

My question is… Is there a better/different/preferred way of refactoring this chunk of code:

if ( bodyClasses.contains("first-class") || bodyClasses.contains("second-class") || bodyClasses.contains("third-class") ) {
        pages.filter((page) => searchAndReplace( page.postType, ".selector" ));
}

I tried using reduce() but quickly learned I'd need to break the reduce prematurely as soon as the first iteration returned true. I feel like the if statement makes sense here but I'm just curious.

I know it is a small chunk of code without context, but the question is in regards concept and not functionality.

And to anyone that responds, I thank you in advance!


Solution

  • To get away the or, match against .some array values:

    if(["first-class", "second-class", "third-class"].some(cls => bodyClasses.contains(cls)))
     /*...*/;
    

    and I wouldn't use .filter if you are not doing anything with the returned values, then just use .forEach.