Replacing "||" Conditionals in Javascript

72 Views Asked by At

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!

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

When it comes down to it the || will likely need to be somewhere but maybe we can tuck them away. I like to use predicates in my if clauses to increase readability and create reusable functions.

const hasSupport = classes =>
  classes.some(cls => cls === "class1" || cls === "class2" || cls === "class3");

if (hasSupport(bodyClasses)) { ... }

The last part to think about is inside your if statement. That filter will return a new list but you aren't storing the data anywhere. So, if you actually want a new list then store it in a variable:

const supportedPages = hasSupport(bodyClasses) 
  ?  pages.filter(...) 
  : []

If you instead want those side effects then use a forEach loop:

if (hasSupport(bodyClasses) { pages.forEach(...) }