jeudi 25 avril 2019

Writing lots of else if statements shorter

I am currently working on a piece of code that is working but I seem to have to repeat one part for about 50 times and this could be probably coded better. So that it is just one shortcode.

This is the part that I have to repeat:

else if (!localStorage.getItem('2Load') && localStorage.getItem('retriever') && (localStorage.getItem('TotalProducts') >= '2')) {
    $('#g-header').show();
    localStorage['2Load'] = true;
    localStorage['item'] = '2';
    var qm2 = $('.qvid-2').text();
    var qmProductID = qm2,
        qmProductIDpos = qmProductID.indexOf("{") + 1;
    qmProductID = qmProductID.slice(qmProductIDpos, qmProductID.lastIndexOf("}"));
    var qmQuantity = qm2,
        qmQuantitypos = qmQuantity.indexOf("[") + 1;
    qmQuantity = qmQuantity.slice(qmQuantitypos, qmQuantity.lastIndexOf(" x]"));
    if (debug === true) {
        alert('qmProductID:' + qmProductID);
        alert('qmQuantity:' + qmQuantity);
    }

    $('.quantity-modifier').onchange(updateNrOfProductsInCart(qmProductID, '1'));
    window.location.reload();
}

I need this code up to a minimal of 50 but it would be so much better if it could be condensed. But sadly I don't have a good grip on how to do that.

Currently I need to copy it and then replace all 2's to 3's. And then 3>4 etc.

The full code can be found here: https://jsfiddle.net/purple11111/fx3mw8qu/3/

Aucun commentaire:

Enregistrer un commentaire