-1

Вот код с повторяющимися кусками, который никак грамотно не получается сократить, завернуть в функцию или метод. Меня почему-то заклинило, прошу помощи

  /*  глобальные переменные */
  var totalSumm = 0,
      protVal = 0,
      gainVal = 0,
      crea300Val = 0,
      crea500Val = 0,
      bcaa300Val = 0,
      bcaa500Val = 0,
      protWeight = 0,
      gainWeight = 0,
      crea300Weight = 0,
      crea500Weight = 0,
      bcaa300Weight = 0,
      bcaa500Weight = 0,
      fullWeight = 0,
      valWheight = 0;

  var fullAmount = function(){
    fullWeight = parseFloat(protWeight+gainWeight+crea300Weight+crea500Weight+bcaa300Weight+bcaa500Weight) * 1.1;
    switch (true) {
      case (fullWeight == 0) : valWheight =   0; break;
      case (fullWeight < 0.5): valWheight =  30; break;
      case (fullWeight < 1)  : valWheight =  35; break;
      case (fullWeight < 2)  : valWheight =  40; break;
      case (fullWeight < 5)  : valWheight =  45; break;
      case (fullWeight < 10) : valWheight =  50; break;
      case (fullWeight < 15) : valWheight =  65; break;
      case (fullWeight < 20) : valWheight =  80; break;
      case (fullWeight < 25) : valWheight =  95; break;
      case (fullWeight > 25) : valWheight = 100; break;
      default: valWheight = 45; break;
    }
    var wheyProtPrice = parseInt(priceList.wheyProt.price[protVal] || 0),
        gainerPrice = parseInt(priceList.gainer.price[gainVal] || 0),
        crea300Price = parseInt(priceList.crea300.price[crea300Val] || 0),
        crea500Price = parseInt(priceList.crea500.price[crea500Val] || 0),
        bcaa300Price = parseInt(priceList.bcaa300.price[bcaa300Val] || 0),
        bcaa500Price = parseInt(priceList.bcaa500.price[bcaa500Val] || 0);
    totalSumm = parseInt(wheyProtPrice + gainerPrice + crea300Price + crea500Price + bcaa300Price + bcaa500Price + valWheight);
    $('#summ').val(totalSumm);
  };

  var prodStart = function(){
    if($('#prot').prop('checked')){
      $('#prot').val('Да');
      if (protVal < 1){$('#prot-quantity').val('1')}
      protVal = $('#prot-quantity').val() * 1;
      protWeight = protVal * priceList.wheyProt.weightCf * 1;
    }else{
      $('#prot').val('Нет');
      protVal = 0;
      protWeight = 0;
    };
    if($('#gain').prop('checked')){
      $('#gain').val('Да');
      if (gainVal < 1){$('#gain-quantity').val('1')}
      gainVal = $('#gain-quantity').val() * 1;
      gainWeight = gainVal * priceList.gainer.weightCf * 1;
    }else{
      $('#gain').val('Нет');
      gainVal = 0;
      gainWeight = 0;
    };
    if($('#crea-300').prop('checked')){
      $('#crea-300').val('Да');
      if (crea300Val < 1){$('#crea-300-quantity').val('1')}
      crea300Val = $('#crea-300-quantity').val() * 1;
      crea300Weight = crea300Val * priceList.crea300.weightCf * 1;
    }else{
      $('#crea-300').val('Нет');
      crea300Val = 0;
      crea300Weight = 0;
    };
    if($('#crea-500').prop('checked')){
      $('#crea-500').val('Да');
      if (crea500Val < 1){$('#crea-500-quantity').val('1')}
      crea500Val = $('#crea-500-quantity').val() * 1;
      crea500Weight = crea500Val * priceList.crea500.weightCf * 1;
    }else{
      $('#crea-500').val('Нет');
      crea500Val = 0;
      crea500Weight = 0;
    };
    if($('#bcaa-300').prop('checked')){
      $('#bcaa-300').val('Да');
      if (bcaa300Val < 1){$('#bcaa-300-quantity').val('1')}
      bcaa300Val = $('#bcaa-300-quantity').val() * 1;
      bcaa300Weight = bcaa300Val * priceList.bcaa300.weightCf * 1;
    }else{
      $('#bcaa-300').val('Нет');
      bcaa300Val = 0;
      bcaa300Weight = 0;
    };
    if($('#bcaa-500').prop('checked')){
      $('#bcaa-500').val('Да');
      if (bcaa500Val < 1){$('#bcaa-500-quantity').val('1')}
      bcaa500Val = $('#bcaa-500-quantity').val() * 1;
      bcaa500Weight = bcaa500Val * priceList.bcaa500.weightCf * 1;
    }else{
      $('#bcaa-500').val('Нет');
      bcaa500Val = 0;
      bcaa500Weight = 0;
    };
  };

  prodStart();
  fullAmount();

  $('#prot, #gain, #crea-300, #crea-500, #bcaa-300, #bcaa-500, #prot-quantity, #gain-quantity, #crea-300-quantity, #crea-500-quantity, #bcaa-300-quantity, #bcaa-500-quantity').change(function(){
    prodStart(this);
    fullAmount();
  });
4
  • html код тоже приложите, пожалуйста. 4 мая 2018 в 23:44
  • И явно не хватает priceList 5 мая 2018 в 3:48
  • ни html, ни priceList ничем не поможет сократить код 5 мая 2018 в 10:55
  • @reFactorPro, нужна структура priceList: какие поля есть в этом объекте? только те, которые показаны в коде или еще какие-то?
    – Grundy
    5 мая 2018 в 18:41

1 ответ 1

1

1) fullWeight == 0 - плохо, т.к. нестрогое сравнение. Если в fullWeight будет строка со значение "0", то будет true. Нужно строгое сравнение использовать fullWeight === 0.

2) Как минимум, весь prodStart можно переписать, если вместо текущего задания переменных задать их одним объектом:

var globalVars = {
    totalSumm : 0,
    protVal : 0,
    gainVal : 0,
    crea300Val : 0,
    crea500Val : 0,
    bcaa300Val : 0,
    bcaa500Val : 0,
    protWeight : 0,
    gainWeight : 0,
    crea300Weight : 0,
    crea500Weight : 0,
    bcaa300Weight : 0,
    bcaa500Weight : 0,
    fullWeight : 0,
    valWheight : 0
};

А сам метод переписать так:

var prodStart = function(){
    doThings("prot", "wheyProt");
    doThings("gain", "gainer");
    doThings("crea-300", "crea300");
    doThings("crea-500", "crea500");
    doThings("bcaa-300", "bcaa300");
    doThings("bcaa-500", "bcaa500");
};

function doThings(key, listKey) {
    var varKey = key.replace("-", "");
    var jKey = '#' + key;
    var jqkey = '#' + key + '-quantity';
    var valKey = key + "Val";
    var weightKey = key + "Weight";

    if ($(jKey).prop('checked')) {
        $(jKey).val('Да');
        if (globalVars[varKey] < 1)
            $(jqkey).val('1');

        globalVars[valKey] = $(jqkey).val() * 1;
        globalVars[weightKey] = globalVars[valKey] * priceList[listKey].weightCf * 1;
    } else {
        $(jKey).val('Нет');
        globalVars[valKey] = 0;
        globalVars[weightKey] = 0;
    }
}

Остаётся только fullAmount слегка переписать.

Т.к. html разметки не привели в вопросе, то проверить не могу. Но, как минимум, думаю, ход мысли понятен будет.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.