У меня была функция, которая принимала несколько аргументов.
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 `- ${formatted}`;
if (value > 0) return `+ ${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);
Вам нужно только установить параметры, которые вы хотите установить, и это легче понять вВзгляд.
Мне было интересно, есть ли лучший способ сделать это, хотя?Любые советы?
Спасибо!