Reduce code and simplify the logic of IF-THEN-ELSE block












4















I'm having a really hard time understanding how to best utilize if else statements. For example:



$('.qty_input').keyup(function () {
var qtyValue = $('.qty_input').val();
if (qtyValue >= number1 && qtyValue <= number10){
if ($('option[value="2"]').parent("span").length) {$('option[value="2"]').unwrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {$('option[value="3"]').unwrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {$('option[value="4"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {$('option[value="1"]').unwrap('<span/>')}
if ($('option[value="2"]').parent("span").length) {}else {$('option[value="2"]').wrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {}else {$('option[value="3"]').wrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {}else {$('option[value="4"]').wrap('<span/>')}
}
else if (qtyValue >= number2 && qtyValue <= number20){
if ($('option[value="2"]').parent("span").length) {$('option[value="2"]').unwrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {$('option[value="3"]').unwrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {$('option[value="4"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {$('option[value="1"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {}else {$('option[value="1"]').wrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {}else {$('option[value="3"]').wrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {}else {$('option[value="4"]').wrap('<span/>')}
}
else if (qtyValue >= number3 && qtyValue <= number30){
if ($('option[value="2"]').parent("span").length) {$('option[value="2"]').unwrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {$('option[value="3"]').unwrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {$('option[value="4"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {$('option[value="1"]').unwrap('<span/>')}
if ($('option[value="2"]').parent("span").length) {}else {$('option[value="2"]').wrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {}else {$('option[value="1"]').wrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {}else {$('option[value="4"]').wrap('<span/>')}
}
else if (qtyValue >= number4 && qtyValue <= 999999){
if ($('option[value="2"]').parent("span").length) {$('option[value="2"]').unwrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {$('option[value="3"]').unwrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {$('option[value="4"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {$('option[value="1"]').unwrap('<span/>')}
if ($('option[value="2"]').parent("span").length) {}else {$('option[value="2"]').wrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {}else {$('option[value="3"]').wrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {}else {$('option[value="1"]').wrap('<span/>')}
}});


Does anybody have any suggestions on how I can update this so it's cleaner and more effective? Thanks.










share|improve this question

























  • use switch instead of if

    – Yash Soni
    Nov 27 '18 at 5:11











  • Does the order of the ifs matter?

    – CertainPerformance
    Nov 27 '18 at 5:12











  • What does the HTML look like? Shouldn't options only ever have <select>, <optgroup> or a <datalist> parent, not a span?

    – CertainPerformance
    Nov 27 '18 at 5:15











  • I'm wondering why unwrap immediately followed by wrap on the same node.

    – Randy Casburn
    Nov 27 '18 at 5:17
















4















I'm having a really hard time understanding how to best utilize if else statements. For example:



$('.qty_input').keyup(function () {
var qtyValue = $('.qty_input').val();
if (qtyValue >= number1 && qtyValue <= number10){
if ($('option[value="2"]').parent("span").length) {$('option[value="2"]').unwrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {$('option[value="3"]').unwrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {$('option[value="4"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {$('option[value="1"]').unwrap('<span/>')}
if ($('option[value="2"]').parent("span").length) {}else {$('option[value="2"]').wrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {}else {$('option[value="3"]').wrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {}else {$('option[value="4"]').wrap('<span/>')}
}
else if (qtyValue >= number2 && qtyValue <= number20){
if ($('option[value="2"]').parent("span").length) {$('option[value="2"]').unwrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {$('option[value="3"]').unwrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {$('option[value="4"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {$('option[value="1"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {}else {$('option[value="1"]').wrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {}else {$('option[value="3"]').wrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {}else {$('option[value="4"]').wrap('<span/>')}
}
else if (qtyValue >= number3 && qtyValue <= number30){
if ($('option[value="2"]').parent("span").length) {$('option[value="2"]').unwrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {$('option[value="3"]').unwrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {$('option[value="4"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {$('option[value="1"]').unwrap('<span/>')}
if ($('option[value="2"]').parent("span").length) {}else {$('option[value="2"]').wrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {}else {$('option[value="1"]').wrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {}else {$('option[value="4"]').wrap('<span/>')}
}
else if (qtyValue >= number4 && qtyValue <= 999999){
if ($('option[value="2"]').parent("span").length) {$('option[value="2"]').unwrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {$('option[value="3"]').unwrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {$('option[value="4"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {$('option[value="1"]').unwrap('<span/>')}
if ($('option[value="2"]').parent("span").length) {}else {$('option[value="2"]').wrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {}else {$('option[value="3"]').wrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {}else {$('option[value="1"]').wrap('<span/>')}
}});


Does anybody have any suggestions on how I can update this so it's cleaner and more effective? Thanks.










share|improve this question

























  • use switch instead of if

    – Yash Soni
    Nov 27 '18 at 5:11











  • Does the order of the ifs matter?

    – CertainPerformance
    Nov 27 '18 at 5:12











  • What does the HTML look like? Shouldn't options only ever have <select>, <optgroup> or a <datalist> parent, not a span?

    – CertainPerformance
    Nov 27 '18 at 5:15











  • I'm wondering why unwrap immediately followed by wrap on the same node.

    – Randy Casburn
    Nov 27 '18 at 5:17














4












4








4








I'm having a really hard time understanding how to best utilize if else statements. For example:



$('.qty_input').keyup(function () {
var qtyValue = $('.qty_input').val();
if (qtyValue >= number1 && qtyValue <= number10){
if ($('option[value="2"]').parent("span").length) {$('option[value="2"]').unwrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {$('option[value="3"]').unwrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {$('option[value="4"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {$('option[value="1"]').unwrap('<span/>')}
if ($('option[value="2"]').parent("span").length) {}else {$('option[value="2"]').wrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {}else {$('option[value="3"]').wrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {}else {$('option[value="4"]').wrap('<span/>')}
}
else if (qtyValue >= number2 && qtyValue <= number20){
if ($('option[value="2"]').parent("span").length) {$('option[value="2"]').unwrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {$('option[value="3"]').unwrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {$('option[value="4"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {$('option[value="1"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {}else {$('option[value="1"]').wrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {}else {$('option[value="3"]').wrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {}else {$('option[value="4"]').wrap('<span/>')}
}
else if (qtyValue >= number3 && qtyValue <= number30){
if ($('option[value="2"]').parent("span").length) {$('option[value="2"]').unwrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {$('option[value="3"]').unwrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {$('option[value="4"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {$('option[value="1"]').unwrap('<span/>')}
if ($('option[value="2"]').parent("span").length) {}else {$('option[value="2"]').wrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {}else {$('option[value="1"]').wrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {}else {$('option[value="4"]').wrap('<span/>')}
}
else if (qtyValue >= number4 && qtyValue <= 999999){
if ($('option[value="2"]').parent("span").length) {$('option[value="2"]').unwrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {$('option[value="3"]').unwrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {$('option[value="4"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {$('option[value="1"]').unwrap('<span/>')}
if ($('option[value="2"]').parent("span").length) {}else {$('option[value="2"]').wrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {}else {$('option[value="3"]').wrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {}else {$('option[value="1"]').wrap('<span/>')}
}});


Does anybody have any suggestions on how I can update this so it's cleaner and more effective? Thanks.










share|improve this question
















I'm having a really hard time understanding how to best utilize if else statements. For example:



$('.qty_input').keyup(function () {
var qtyValue = $('.qty_input').val();
if (qtyValue >= number1 && qtyValue <= number10){
if ($('option[value="2"]').parent("span").length) {$('option[value="2"]').unwrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {$('option[value="3"]').unwrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {$('option[value="4"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {$('option[value="1"]').unwrap('<span/>')}
if ($('option[value="2"]').parent("span").length) {}else {$('option[value="2"]').wrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {}else {$('option[value="3"]').wrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {}else {$('option[value="4"]').wrap('<span/>')}
}
else if (qtyValue >= number2 && qtyValue <= number20){
if ($('option[value="2"]').parent("span").length) {$('option[value="2"]').unwrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {$('option[value="3"]').unwrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {$('option[value="4"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {$('option[value="1"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {}else {$('option[value="1"]').wrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {}else {$('option[value="3"]').wrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {}else {$('option[value="4"]').wrap('<span/>')}
}
else if (qtyValue >= number3 && qtyValue <= number30){
if ($('option[value="2"]').parent("span").length) {$('option[value="2"]').unwrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {$('option[value="3"]').unwrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {$('option[value="4"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {$('option[value="1"]').unwrap('<span/>')}
if ($('option[value="2"]').parent("span").length) {}else {$('option[value="2"]').wrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {}else {$('option[value="1"]').wrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {}else {$('option[value="4"]').wrap('<span/>')}
}
else if (qtyValue >= number4 && qtyValue <= 999999){
if ($('option[value="2"]').parent("span").length) {$('option[value="2"]').unwrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {$('option[value="3"]').unwrap('<span/>')}
if ($('option[value="4"]').parent("span").length) {$('option[value="4"]').unwrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {$('option[value="1"]').unwrap('<span/>')}
if ($('option[value="2"]').parent("span").length) {}else {$('option[value="2"]').wrap('<span/>')}
if ($('option[value="3"]').parent("span").length) {}else {$('option[value="3"]').wrap('<span/>')}
if ($('option[value="1"]').parent("span").length) {}else {$('option[value="1"]').wrap('<span/>')}
}});


Does anybody have any suggestions on how I can update this so it's cleaner and more effective? Thanks.







javascript jquery if-statement






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 27 '18 at 5:35









Ahmad

8,27043663




8,27043663










asked Nov 27 '18 at 5:07









BorisBoris

628




628













  • use switch instead of if

    – Yash Soni
    Nov 27 '18 at 5:11











  • Does the order of the ifs matter?

    – CertainPerformance
    Nov 27 '18 at 5:12











  • What does the HTML look like? Shouldn't options only ever have <select>, <optgroup> or a <datalist> parent, not a span?

    – CertainPerformance
    Nov 27 '18 at 5:15











  • I'm wondering why unwrap immediately followed by wrap on the same node.

    – Randy Casburn
    Nov 27 '18 at 5:17



















  • use switch instead of if

    – Yash Soni
    Nov 27 '18 at 5:11











  • Does the order of the ifs matter?

    – CertainPerformance
    Nov 27 '18 at 5:12











  • What does the HTML look like? Shouldn't options only ever have <select>, <optgroup> or a <datalist> parent, not a span?

    – CertainPerformance
    Nov 27 '18 at 5:15











  • I'm wondering why unwrap immediately followed by wrap on the same node.

    – Randy Casburn
    Nov 27 '18 at 5:17

















use switch instead of if

– Yash Soni
Nov 27 '18 at 5:11





use switch instead of if

– Yash Soni
Nov 27 '18 at 5:11













Does the order of the ifs matter?

– CertainPerformance
Nov 27 '18 at 5:12





Does the order of the ifs matter?

– CertainPerformance
Nov 27 '18 at 5:12













What does the HTML look like? Shouldn't options only ever have <select>, <optgroup> or a <datalist> parent, not a span?

– CertainPerformance
Nov 27 '18 at 5:15





What does the HTML look like? Shouldn't options only ever have <select>, <optgroup> or a <datalist> parent, not a span?

– CertainPerformance
Nov 27 '18 at 5:15













I'm wondering why unwrap immediately followed by wrap on the same node.

– Randy Casburn
Nov 27 '18 at 5:17





I'm wondering why unwrap immediately followed by wrap on the same node.

– Randy Casburn
Nov 27 '18 at 5:17












2 Answers
2






active

oldest

votes


















1














Looking at your code, I noticed some patterns that can be converted into functions, or taken away at once.



$('.qty_input').keyup(function () {

var qtyValue = $('.qty_input').val();
// these 4 statements are executed no matter what.
// there is no point in duplicating them in each if-then block
for(var i=1; i<=4; i++) {
if ($('option[value="'+i+'"]').parent("span").length) {
$('option[value="'+i+'"]').unwrap('<span/>');
}
}


// the pattern for the next part is simple
// execute 4 statements of jQuery but exclude one part per each if-then block
if (qtyValue >= number1 && qtyValue <= number10) { exclude(1); }
else if (qtyValue >= number2 && qtyValue <= number20) { exclude(2); }
else if (qtyValue >= number3 && qtyValue <= number30) { exclude(3); }
else if (qtyValue >= number4 && qtyValue <= 999999) { exclude(4); }

function exclude(num) {
// loop from 1 to 4 to execute the same for each part
// but only exclude the one statement that is passed
// into the function
for(var i=1; i<=4; i++) {
if(i!=num) {
if (!$('option[value="'+i+'"]').parent("span").length) {
$('option[value="'+i+'"]').wrap('<span/>')
}
}
}
}
});





share|improve this answer































    0














    One option would be to create an object of the jQuery collections (for each value=). Because the unwrapping process is the same for every outer qtyValue condition, you can run that part of the code unconditionally, by iterating over the object's values and unwrapping if the item's parent is a span. Then, make a function that takes as a parameter the value you want to ignore when wrapping, and iterate over the values of the object that don't have that value.



    It would also be nice if you could change your standalone number# variables into an array of ranges, for example



    [
    [10, 20], // [number1, number10]
    [21, 30], // [number2, number20]


    That'll not only be better for making your code concise when defining those ranges, but it'll also make it easier to .find the appropriate index to call wrap with - replace the four if / else if statements at the end with something like:



    const indexToIgnore = 1 + ranges.findIndex(([min, max]) => qtyValue >= min && qtyValue <= max);
    wrap(indexToIgnore);


    In full:



    $('.qty_input').keyup(function () {
    const qtyValue = $('.qty_input').val();
    const options = {
    1: $('option[value="1"]'),
    2: $('option[value="2"]'),
    3: $('option[value="3"]'),
    4: $('option[value="4"]'),
    };
    // unwrap all, code is the same regardless of `if` statement::
    Object.values(options).forEach((option) => {
    if (option.parent("span").length) {
    option.unwrap('<span/>')
    }
    });
    function wrap(keyToIgnore) {
    keyToIgnore = String(keyToIgnore); // object properties are strings
    Object.entries(options)
    .filter(([key]) => key !== keyToIgnore)
    .forEach(([, option]) => {
    if (!option.parent("span").length) {
    option.wrap('<span/>')
    }
    });
    }
    const indexToIgnore = 1 + ranges.findIndex(([min, max]) => qtyValue >= min && qtyValue <= max);
    wrap(indexToIgnore);
    });





    share|improve this answer


























    • How are you excluding the one value per condition? I'm sorry I haven't dived into straight Javascript, I've only taken in jQuery. I can sort of understand your function wrap(keyToIgnore). Thanks for your efforts.

      – Boris
      Nov 28 '18 at 6:31











    • jQuery is Javascript - jQuery is just a Javascript library, which runs on Javascript code and syntax, and is interacted with using Javascript code and syntax :)

      – CertainPerformance
      Nov 28 '18 at 6:38











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53493086%2freduce-code-and-simplify-the-logic-of-if-then-else-block%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Looking at your code, I noticed some patterns that can be converted into functions, or taken away at once.



    $('.qty_input').keyup(function () {

    var qtyValue = $('.qty_input').val();
    // these 4 statements are executed no matter what.
    // there is no point in duplicating them in each if-then block
    for(var i=1; i<=4; i++) {
    if ($('option[value="'+i+'"]').parent("span").length) {
    $('option[value="'+i+'"]').unwrap('<span/>');
    }
    }


    // the pattern for the next part is simple
    // execute 4 statements of jQuery but exclude one part per each if-then block
    if (qtyValue >= number1 && qtyValue <= number10) { exclude(1); }
    else if (qtyValue >= number2 && qtyValue <= number20) { exclude(2); }
    else if (qtyValue >= number3 && qtyValue <= number30) { exclude(3); }
    else if (qtyValue >= number4 && qtyValue <= 999999) { exclude(4); }

    function exclude(num) {
    // loop from 1 to 4 to execute the same for each part
    // but only exclude the one statement that is passed
    // into the function
    for(var i=1; i<=4; i++) {
    if(i!=num) {
    if (!$('option[value="'+i+'"]').parent("span").length) {
    $('option[value="'+i+'"]').wrap('<span/>')
    }
    }
    }
    }
    });





    share|improve this answer




























      1














      Looking at your code, I noticed some patterns that can be converted into functions, or taken away at once.



      $('.qty_input').keyup(function () {

      var qtyValue = $('.qty_input').val();
      // these 4 statements are executed no matter what.
      // there is no point in duplicating them in each if-then block
      for(var i=1; i<=4; i++) {
      if ($('option[value="'+i+'"]').parent("span").length) {
      $('option[value="'+i+'"]').unwrap('<span/>');
      }
      }


      // the pattern for the next part is simple
      // execute 4 statements of jQuery but exclude one part per each if-then block
      if (qtyValue >= number1 && qtyValue <= number10) { exclude(1); }
      else if (qtyValue >= number2 && qtyValue <= number20) { exclude(2); }
      else if (qtyValue >= number3 && qtyValue <= number30) { exclude(3); }
      else if (qtyValue >= number4 && qtyValue <= 999999) { exclude(4); }

      function exclude(num) {
      // loop from 1 to 4 to execute the same for each part
      // but only exclude the one statement that is passed
      // into the function
      for(var i=1; i<=4; i++) {
      if(i!=num) {
      if (!$('option[value="'+i+'"]').parent("span").length) {
      $('option[value="'+i+'"]').wrap('<span/>')
      }
      }
      }
      }
      });





      share|improve this answer


























        1












        1








        1







        Looking at your code, I noticed some patterns that can be converted into functions, or taken away at once.



        $('.qty_input').keyup(function () {

        var qtyValue = $('.qty_input').val();
        // these 4 statements are executed no matter what.
        // there is no point in duplicating them in each if-then block
        for(var i=1; i<=4; i++) {
        if ($('option[value="'+i+'"]').parent("span").length) {
        $('option[value="'+i+'"]').unwrap('<span/>');
        }
        }


        // the pattern for the next part is simple
        // execute 4 statements of jQuery but exclude one part per each if-then block
        if (qtyValue >= number1 && qtyValue <= number10) { exclude(1); }
        else if (qtyValue >= number2 && qtyValue <= number20) { exclude(2); }
        else if (qtyValue >= number3 && qtyValue <= number30) { exclude(3); }
        else if (qtyValue >= number4 && qtyValue <= 999999) { exclude(4); }

        function exclude(num) {
        // loop from 1 to 4 to execute the same for each part
        // but only exclude the one statement that is passed
        // into the function
        for(var i=1; i<=4; i++) {
        if(i!=num) {
        if (!$('option[value="'+i+'"]').parent("span").length) {
        $('option[value="'+i+'"]').wrap('<span/>')
        }
        }
        }
        }
        });





        share|improve this answer













        Looking at your code, I noticed some patterns that can be converted into functions, or taken away at once.



        $('.qty_input').keyup(function () {

        var qtyValue = $('.qty_input').val();
        // these 4 statements are executed no matter what.
        // there is no point in duplicating them in each if-then block
        for(var i=1; i<=4; i++) {
        if ($('option[value="'+i+'"]').parent("span").length) {
        $('option[value="'+i+'"]').unwrap('<span/>');
        }
        }


        // the pattern for the next part is simple
        // execute 4 statements of jQuery but exclude one part per each if-then block
        if (qtyValue >= number1 && qtyValue <= number10) { exclude(1); }
        else if (qtyValue >= number2 && qtyValue <= number20) { exclude(2); }
        else if (qtyValue >= number3 && qtyValue <= number30) { exclude(3); }
        else if (qtyValue >= number4 && qtyValue <= 999999) { exclude(4); }

        function exclude(num) {
        // loop from 1 to 4 to execute the same for each part
        // but only exclude the one statement that is passed
        // into the function
        for(var i=1; i<=4; i++) {
        if(i!=num) {
        if (!$('option[value="'+i+'"]').parent("span").length) {
        $('option[value="'+i+'"]').wrap('<span/>')
        }
        }
        }
        }
        });






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 27 '18 at 5:24









        AhmadAhmad

        8,27043663




        8,27043663

























            0














            One option would be to create an object of the jQuery collections (for each value=). Because the unwrapping process is the same for every outer qtyValue condition, you can run that part of the code unconditionally, by iterating over the object's values and unwrapping if the item's parent is a span. Then, make a function that takes as a parameter the value you want to ignore when wrapping, and iterate over the values of the object that don't have that value.



            It would also be nice if you could change your standalone number# variables into an array of ranges, for example



            [
            [10, 20], // [number1, number10]
            [21, 30], // [number2, number20]


            That'll not only be better for making your code concise when defining those ranges, but it'll also make it easier to .find the appropriate index to call wrap with - replace the four if / else if statements at the end with something like:



            const indexToIgnore = 1 + ranges.findIndex(([min, max]) => qtyValue >= min && qtyValue <= max);
            wrap(indexToIgnore);


            In full:



            $('.qty_input').keyup(function () {
            const qtyValue = $('.qty_input').val();
            const options = {
            1: $('option[value="1"]'),
            2: $('option[value="2"]'),
            3: $('option[value="3"]'),
            4: $('option[value="4"]'),
            };
            // unwrap all, code is the same regardless of `if` statement::
            Object.values(options).forEach((option) => {
            if (option.parent("span").length) {
            option.unwrap('<span/>')
            }
            });
            function wrap(keyToIgnore) {
            keyToIgnore = String(keyToIgnore); // object properties are strings
            Object.entries(options)
            .filter(([key]) => key !== keyToIgnore)
            .forEach(([, option]) => {
            if (!option.parent("span").length) {
            option.wrap('<span/>')
            }
            });
            }
            const indexToIgnore = 1 + ranges.findIndex(([min, max]) => qtyValue >= min && qtyValue <= max);
            wrap(indexToIgnore);
            });





            share|improve this answer


























            • How are you excluding the one value per condition? I'm sorry I haven't dived into straight Javascript, I've only taken in jQuery. I can sort of understand your function wrap(keyToIgnore). Thanks for your efforts.

              – Boris
              Nov 28 '18 at 6:31











            • jQuery is Javascript - jQuery is just a Javascript library, which runs on Javascript code and syntax, and is interacted with using Javascript code and syntax :)

              – CertainPerformance
              Nov 28 '18 at 6:38
















            0














            One option would be to create an object of the jQuery collections (for each value=). Because the unwrapping process is the same for every outer qtyValue condition, you can run that part of the code unconditionally, by iterating over the object's values and unwrapping if the item's parent is a span. Then, make a function that takes as a parameter the value you want to ignore when wrapping, and iterate over the values of the object that don't have that value.



            It would also be nice if you could change your standalone number# variables into an array of ranges, for example



            [
            [10, 20], // [number1, number10]
            [21, 30], // [number2, number20]


            That'll not only be better for making your code concise when defining those ranges, but it'll also make it easier to .find the appropriate index to call wrap with - replace the four if / else if statements at the end with something like:



            const indexToIgnore = 1 + ranges.findIndex(([min, max]) => qtyValue >= min && qtyValue <= max);
            wrap(indexToIgnore);


            In full:



            $('.qty_input').keyup(function () {
            const qtyValue = $('.qty_input').val();
            const options = {
            1: $('option[value="1"]'),
            2: $('option[value="2"]'),
            3: $('option[value="3"]'),
            4: $('option[value="4"]'),
            };
            // unwrap all, code is the same regardless of `if` statement::
            Object.values(options).forEach((option) => {
            if (option.parent("span").length) {
            option.unwrap('<span/>')
            }
            });
            function wrap(keyToIgnore) {
            keyToIgnore = String(keyToIgnore); // object properties are strings
            Object.entries(options)
            .filter(([key]) => key !== keyToIgnore)
            .forEach(([, option]) => {
            if (!option.parent("span").length) {
            option.wrap('<span/>')
            }
            });
            }
            const indexToIgnore = 1 + ranges.findIndex(([min, max]) => qtyValue >= min && qtyValue <= max);
            wrap(indexToIgnore);
            });





            share|improve this answer


























            • How are you excluding the one value per condition? I'm sorry I haven't dived into straight Javascript, I've only taken in jQuery. I can sort of understand your function wrap(keyToIgnore). Thanks for your efforts.

              – Boris
              Nov 28 '18 at 6:31











            • jQuery is Javascript - jQuery is just a Javascript library, which runs on Javascript code and syntax, and is interacted with using Javascript code and syntax :)

              – CertainPerformance
              Nov 28 '18 at 6:38














            0












            0








            0







            One option would be to create an object of the jQuery collections (for each value=). Because the unwrapping process is the same for every outer qtyValue condition, you can run that part of the code unconditionally, by iterating over the object's values and unwrapping if the item's parent is a span. Then, make a function that takes as a parameter the value you want to ignore when wrapping, and iterate over the values of the object that don't have that value.



            It would also be nice if you could change your standalone number# variables into an array of ranges, for example



            [
            [10, 20], // [number1, number10]
            [21, 30], // [number2, number20]


            That'll not only be better for making your code concise when defining those ranges, but it'll also make it easier to .find the appropriate index to call wrap with - replace the four if / else if statements at the end with something like:



            const indexToIgnore = 1 + ranges.findIndex(([min, max]) => qtyValue >= min && qtyValue <= max);
            wrap(indexToIgnore);


            In full:



            $('.qty_input').keyup(function () {
            const qtyValue = $('.qty_input').val();
            const options = {
            1: $('option[value="1"]'),
            2: $('option[value="2"]'),
            3: $('option[value="3"]'),
            4: $('option[value="4"]'),
            };
            // unwrap all, code is the same regardless of `if` statement::
            Object.values(options).forEach((option) => {
            if (option.parent("span").length) {
            option.unwrap('<span/>')
            }
            });
            function wrap(keyToIgnore) {
            keyToIgnore = String(keyToIgnore); // object properties are strings
            Object.entries(options)
            .filter(([key]) => key !== keyToIgnore)
            .forEach(([, option]) => {
            if (!option.parent("span").length) {
            option.wrap('<span/>')
            }
            });
            }
            const indexToIgnore = 1 + ranges.findIndex(([min, max]) => qtyValue >= min && qtyValue <= max);
            wrap(indexToIgnore);
            });





            share|improve this answer















            One option would be to create an object of the jQuery collections (for each value=). Because the unwrapping process is the same for every outer qtyValue condition, you can run that part of the code unconditionally, by iterating over the object's values and unwrapping if the item's parent is a span. Then, make a function that takes as a parameter the value you want to ignore when wrapping, and iterate over the values of the object that don't have that value.



            It would also be nice if you could change your standalone number# variables into an array of ranges, for example



            [
            [10, 20], // [number1, number10]
            [21, 30], // [number2, number20]


            That'll not only be better for making your code concise when defining those ranges, but it'll also make it easier to .find the appropriate index to call wrap with - replace the four if / else if statements at the end with something like:



            const indexToIgnore = 1 + ranges.findIndex(([min, max]) => qtyValue >= min && qtyValue <= max);
            wrap(indexToIgnore);


            In full:



            $('.qty_input').keyup(function () {
            const qtyValue = $('.qty_input').val();
            const options = {
            1: $('option[value="1"]'),
            2: $('option[value="2"]'),
            3: $('option[value="3"]'),
            4: $('option[value="4"]'),
            };
            // unwrap all, code is the same regardless of `if` statement::
            Object.values(options).forEach((option) => {
            if (option.parent("span").length) {
            option.unwrap('<span/>')
            }
            });
            function wrap(keyToIgnore) {
            keyToIgnore = String(keyToIgnore); // object properties are strings
            Object.entries(options)
            .filter(([key]) => key !== keyToIgnore)
            .forEach(([, option]) => {
            if (!option.parent("span").length) {
            option.wrap('<span/>')
            }
            });
            }
            const indexToIgnore = 1 + ranges.findIndex(([min, max]) => qtyValue >= min && qtyValue <= max);
            wrap(indexToIgnore);
            });






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 27 '18 at 5:29

























            answered Nov 27 '18 at 5:24









            CertainPerformanceCertainPerformance

            88.4k154775




            88.4k154775













            • How are you excluding the one value per condition? I'm sorry I haven't dived into straight Javascript, I've only taken in jQuery. I can sort of understand your function wrap(keyToIgnore). Thanks for your efforts.

              – Boris
              Nov 28 '18 at 6:31











            • jQuery is Javascript - jQuery is just a Javascript library, which runs on Javascript code and syntax, and is interacted with using Javascript code and syntax :)

              – CertainPerformance
              Nov 28 '18 at 6:38



















            • How are you excluding the one value per condition? I'm sorry I haven't dived into straight Javascript, I've only taken in jQuery. I can sort of understand your function wrap(keyToIgnore). Thanks for your efforts.

              – Boris
              Nov 28 '18 at 6:31











            • jQuery is Javascript - jQuery is just a Javascript library, which runs on Javascript code and syntax, and is interacted with using Javascript code and syntax :)

              – CertainPerformance
              Nov 28 '18 at 6:38

















            How are you excluding the one value per condition? I'm sorry I haven't dived into straight Javascript, I've only taken in jQuery. I can sort of understand your function wrap(keyToIgnore). Thanks for your efforts.

            – Boris
            Nov 28 '18 at 6:31





            How are you excluding the one value per condition? I'm sorry I haven't dived into straight Javascript, I've only taken in jQuery. I can sort of understand your function wrap(keyToIgnore). Thanks for your efforts.

            – Boris
            Nov 28 '18 at 6:31













            jQuery is Javascript - jQuery is just a Javascript library, which runs on Javascript code and syntax, and is interacted with using Javascript code and syntax :)

            – CertainPerformance
            Nov 28 '18 at 6:38





            jQuery is Javascript - jQuery is just a Javascript library, which runs on Javascript code and syntax, and is interacted with using Javascript code and syntax :)

            – CertainPerformance
            Nov 28 '18 at 6:38


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53493086%2freduce-code-and-simplify-the-logic-of-if-then-else-block%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

            Calculate evaluation metrics using cross_val_predict sklearn

            Insert data from modal to MySQL (multiple modal on website)