简体   繁体   中英

If/else redundant code in ternary operator

This code works fine, but it looks like it could be optimized as it just reverses the ternary order. Any idea how to achieve that?

if ($("#advanced-search-panel").hasClass("hidden")) {
    adv_text.text(adv_text.text() == "Show advanced search" ? "Hide advanced search" : "Show advanced search");
}else{
    adv_text.text(adv_text.text() == "Hide advanced search" ? "Show advanced search" : "Hide advanced search");
}

Since adv_text.text() only has two possibilities - show and hide - the entire condition

if ($("#advanced-search-painel").hasClass("hidden")) {

is superfluous, because no matter whether the class exists or not, you want to toggle the text from show to hide, or from hide to show, depending on what the text currently is. Your code simplifies to

adv_text.text(
  adv_text.text() == "Show advanced search" ? "Hide advanced search" : "Show advanced search"
);

Another option would be to have an inline element for the part of the text that changes, so that you only have to check and change that.

<div><span class="adv-search-toggle-text">Show</span> advanced search</div>
const span = $('.adv-search-toggle-text');
span.text(span.text() === 'Show' ? 'Hide' : 'Show');

It sounds like the hidden class might have something to do with the text toggling above. If it does, there's a chance you could use CSS rules alone to have Show shown when the hidden class is applied, and Hide shown when the hidden class isn't applied.

As a first step: you want to have "Show advanced search" as a result exactly if both $("#advanced-search-painel").hasClass("hidden") and adv_text.text() == "Show advanced search" are true or both are false, so you could have:

adv_text.text(
    $("#advanced-search-painel").hasClass("hidden") == (adv_text.text() == "Show advanced search")
    ? "Hide advanced search"
    : "Show advanced search"
);

But as @CertainPerformance points out, with the constraint of adv_text.text() having only those two possible values, the if and else branch are achieving exactly the same, so there is no need for the if actually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM