Как провести рефакторинг функции js?

Здравствуйте. Есть ужасно написанная функция смены цены товара, которая учитывает много различных условий. Очевидно, нужно провести рефакторинг, так как сама функция плохо читается. Подскажите, где и что лучше прочесть или какие практики использовать, чтоб такого больше не повторялось. Вот функция для наглядности (прошу прощения заранее):
function changePrice($this = null) {
  if ($this == null) {
      var rel_price =  $('.all_colors_preview.active#rel_colors').find('.item.active .price').attr('data-price'),
          option_price = $('.all_colors_preview.active#option_colors').find('.item.active .option-price').val(),
          prefix = $('.all_colors_preview.active#option_colors').find('.item.active .option-price-prefix').val(),
          price_current = $('.price_wrapper .price_current'),
          option_sizes = $('.option_size.active'),
          quantity = Number($('#inner .quantity_val').text());
  } else {
    var rel_price =  $this.find('#rel_colors.active .item.active .price').attr('data-price'),
        option_price = $this.find('#option_colors.active .item.active .option-price').val(),
        prefix = $this.find('#option_colors.active .item.active .option-price-prefix').val(),
        price_current = $('.price_wrapper .price_current'),
        option_sizes = $this.find('.option_size.active'),
        quantity = Number($this.find('.quantity_val').text());
  }

  if (!quantity) {
    quantity = Number($('#inner .quantity_val').text());
  }

  var current = Number(price_current.attr('data-original-price'));  

  if (rel_price != '' && rel_price != undefined) {
    price_current.attr('data-update-price', rel_price);
    updated = Number(price_current.attr('data-update-price')) * quantity;
    updated = String(updated).replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ')
    price_current.text(updated + ' ₽');
  } else if (option_price != '' && option_price != undefined && prefix != '') {
    if (prefix == '+') {
      update_price = current + Number(option_price);
    } else {
      update_price = current - Number(option_price);
    }

    price_current.attr('data-update-price', update_price);
    update_price = quantity * price_current.attr('data-update-price');
    price_current.text(String(update_price).replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ') + ' ₽');
  } else if (option_price == '') {
    price_current.attr('data-update-price', current);
    current *= quantity;
    price_current.text(String(current).replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ') + ' ₽');
  } else {
    return false;
  }

  if (option_sizes && option_sizes.length) {
    if (price_current.attr('data-update-price')) {
      current = Number(price_current.attr('data-update-price')); 
    }
    var option_prefix = option_sizes.find('input[type="hidden"]').attr('data-prefix'),
        option_size_price = option_sizes.find('input[type="hidden"]').attr('data-price');
    if (option_prefix == '+') {
      update_price = current + Number(option_size_price);
    } else {
      update_price = current - Number(option_size_price);
    }

    price_current.attr('data-update-price', update_price);
    update_price = quantity * price_current.attr('data-update-price');
    price_current.text(String(update_price).replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ') + ' ₽');
  }
}
  • Вопрос задан
  • 181 просмотр
Решения вопроса 2
Kozack
@Kozack Куратор тега JavaScript
Thinking about a11y
Комментировать
@AndrewRusinas
Как минимум избавиться от var'ов. В идеале разбить на десяток-другой мелких функций с понятными названиями с ограниченным функционалом.

Как пример:
String(current).replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ')

Повторяется многократно, можно вынести.

price_current.text(updated + ' ₽');

Аналогично, можно создать функцию setCurrentPriceText().

И так далее. Всякие формулы, на основе которых формируется цена, etc etc
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы