Чтобы поместить это в функцию JS - PullRequest
0 голосов
/ 04 октября 2018

Есть условие, но оно громоздко, как вы можете уменьшить это?Или напишите функцию, к которой можно обратиться.

if (obj.Language.code == "ru") {
        if (obj.Tariff.typeCalc != 1) {
            if (obj.Price.Discount) {
                t = t + getText(obj.Language.code, 'PriceWithDiscount', [Round(obj.Price.Itog), final_currency]);
            }
            else {
                t = t + getText(obj.Language.code, 'PriceNoDiscount', [Round(obj.Price.Itog), final_currency]);
            }
        }
        else {
            if (obj.Price.Discount) {
                t = t + getText(obj.Language.code, 'PriceWithDiscount', [Round(obj.Price.Itog), obj.Currency.symbol]);
            }
            else {
                t = t + getText(obj.Language.code, 'PriceNoDiscount', [Round(obj.Price.Itog), obj.Currency.symbol]);
            }
        }

дизайн

if (obj.Language.code == "ru") {
}
else {
}

будут часто встречаться, не хотят накапливаться

if (obj.Language.code == "ru") {
            if (obj.Price.Discount) {
                
                t = t + getText(obj.Language.code, 'PriceWithDicountOutCity', [obj.Price.Itog, final_currency, Round(obj.Len.value, final_currency), nextkmprice]);
            }
            else {
                
                t = t + getText(obj.Language.code, 'PriceOutCity', [obj.Price.Itog, final_currency, Round(obj.Len.value, final_currency), nextkmprice]);
            }
        }
        else {
            if (obj.Price.Discount) {
                
                t = t + getText(obj.Language.code, 'PriceWithDicountOutCity', [obj.Price.Itog, obj.Currency.symbol, Round(obj.Len.value, obj.Currency.symbol), nextkmprice]);
            }
            else {
                
                t = t + getText(obj.Language.code, 'PriceOutCity', [obj.Price.Itog, obj.Currency.symbol, Round(obj.Len.value, obj.Currency.symbol), nextkmprice]);
            }
        }

Ответы [ 4 ]

0 голосов
/ 04 октября 2018

Создать функцию, которая принимает два параметра

function fullText(x,y) {
    if(x!=1){
            if (obj.Price.Discount) {
                t = t + getText(obj.Language.code, 'PriceWithDiscount', [Round(obj.Price.Itog), obj.Currency.symbol]);
            }
            else {
                t = t + getText(obj.Language.code, 'PriceNoDiscount', [Round(obj.Price.Itog), obj.Currency.symbol]);
            }
    }
}

Создать другую функцию для кода не ru

fullTextNonRu(x,y){
       if (x) {
            if (y) {
                t = t + getText(obj.Language.code, 'PriceWithDiscount', [Round(obj.Price.Itog), obj.Currency.symbol]);
            }
            else {
                t = t + getText(obj.Language.code, 'PriceNoDiscount', [Round(obj.Price.Itog), obj.Currency.symbol]);
            }
        }
  }

Использование регистра переключателя зависит от obj.Language.code

switch(obj.Language.code){
    case "ru":
        fullText(obj.Tariff.typeCalc ,obj.Price.Discount);
        break;
    default:
        fullTextNonRu(obj.Tariff.typeCalc ,obj.Price.Discount);
        break;
 }
0 голосов
/ 04 октября 2018

Вы можете взять одну внешнюю проверку и два условия.

if (obj.Tariff.typeCalc != 1) {
    t += getText(
        obj.Language.code,
        obj.Price.Discount ? 'PriceWithDiscount' : 'PriceNoDiscount',
        [
            Round(obj.Price.Itog),
            obj.Language.code == "ru" ? final_currency : obj.Currency.symbol
        ]
    );
}

Для последней проблемы вы можете заранее сохранить currency и использовать переменную вместо нескольких операторов условия.

var currency = obj.Language.code == "ru" ? final_currency : obj.Currency.symbol;

t += getText(
    obj.Language.code,
    obj.Price.Discount ? 'PriceWithDicountOutCity' : 'PriceOutCity',
    [
        obj.Price.Itog,
        currency,
        Round(obj.Len.value, currency),
        nextkmprice
    ]
);
0 голосов
/ 04 октября 2018

Возможное использование объекта с функциональными клавишами на основе языка:

function langObj(opts){
    this.tarrif = opts.tarrifType;
    this.symbols = [{
        "au":"$",
        "us":"$"
        // include more
    }];

    this.doStuff = function(args){
        return getText(this.code, (args.discount!=-1)?"Price With Discount":"Price No Discount", [Round(args.itog), this.symbols[args.code] ])
    }
    this.ru = function(args){
        args['code']="ru";
        return this.doStuff(args);
    }

    return this;
}

Имейте в виду, я не знаю, что такое "Itog", поэтому я не могу все это сделать, но основа довольно прямаявперед.Потенциально автоматически заполнять объект функциями и символами из текстового файла или что-то с включенными тарифами?Опять же, я не понимаю контекст, но да.

0 голосов
/ 04 октября 2018

Используйте троичный оператор для установки значений в зависимости от условий.Тогда вы можете избавиться от некоторого избыточного кода.Вы можете упростить это до следующего вида:

        if (obj.Tariff.typeCalc != 1) {
            var priceType = obj.Price.Discount ? 'PriceWithDiscount' : 'PriceNoDiscount';
            var currencyType = obj.Language.code == "ru" ? final_currency : obj.Currency.symbol;
            t = t + getText(obj.Language.code, priceType, [Round(obj.Price.Itog), currencyType]);
        }

ES6, используя let:

        if (obj.Tariff.typeCalc != 1) {
            let priceType = obj.Price.Discount ? 'PriceWithDiscount' : 'PriceNoDiscount';
            let currencyType = obj.Language.code == "ru" ? final_currency : obj.Currency.symbol;
            t = t + getText(obj.Language.code, priceType, [Round(obj.Price.Itog), currencyType]);
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...