OO JavaScript, как мне улучшить этот класс?Есть ли лучший, более чистый способ сделать это? - PullRequest
0 голосов
/ 25 октября 2018

У меня была функция, которая принимала несколько аргументов.

function formatString(Number, option1, option2, option3, option4, option5) {
  // apply options to the string:
  // eg: format to '0.00', append "+", append £ sign etc
  // return formatted Number as String
}

Все опции были необязательными, поэтому их стало немного сложно использовать и понять, что они делают:

formatString(value, null, true, currency, null, true) // thats bad

Итак, я начал думать, как я мог бы облегчить использование, расширение и понимание.Я придумал Класс:

export default class Amount {
  constructor(value) {
    this.value = value;
  }

  set coin(val) {
    this._coin = val;
  }

  set currency(val) {
    this._currency = val;
  }

  set format(format) {
    this._format = format;
  }

  set withCurrencySymbol(val) {
    this._withCurrencySymbol = val;
  }

  set prependPlusOrMinus(val) {
    this._prependPlusOrMinus = val;
  }

  get formatted() {
    let { value } = this;
    if (this._coin && this._currency) {
      value = this.coinToCurrency(this.value, this._coin, this._currency);
    }

    let formatted = `${numeral(Math.abs(value)).format(this._format)}`;
    if (this._currency) formatted = `${currencySymbols[this._currency]}${formatted}`;

    if (this._prependPlusOrMinus) {
      if (value < 0) return `&#45; ${formatted}`;
      if (value > 0) return `&#43; ${formatted}`;
    }

    return formatted;
  }

  coinToCurrency() {
    const { rate } = exchangeRates[this._coin].find(item => item.currency === this._currency);
    return this.value * rate;
  }
}

Это облегчает использование:

  const amount = new Amount(value);
  amount.currency = currency;
  amount.format = format;
  console.log(amount.formatted);

Вам нужно только установить параметры, которые вы хотите установить, и это легче понять вВзгляд.

Мне было интересно, есть ли лучший способ сделать это, хотя?Любые советы?

Спасибо!

1 Ответ

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

Я думаю, что лучше передать параметры в виде объекта, {value: val, currency: cur ...}.и использовать конфигурацию по умолчанию в конструкторе, чтобы уменьшить количество параметров, вводимых при использовании этого класса.

Это пример с одним свойством, которое вы можете сделать то же самое для других свойств

class Amount {
    constructor(opt){
      const defaultOpts= {currency:'$'}
      this.opts=Object.assign(defaultOpts,opt)
    }
    
    getValueWithCurruency(){
      return this.opts.value+this.opts.currency
    }
    
}
    
const foo= new Amount({value:50})    
console.log(foo.getValueWithCurruency())//50$

const fooEuro= new Amount({value:50,currency:"€"})  
console.log(fooEuro.getValueWithCurruency())//50€
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...