Reputation: 2806
I had a function, that would accept multiple arguments.
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
}
All options were optional, so it started to become a little difficult to use and understand what it does:
formatString(value, null, true, currency, null, true) // thats bad
So I began thinking how could I make it easier to use, to extend and to understand. I came up with a Class:
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;
}
}
It makes it easier to use:
const amount = new Amount(value);
amount.currency = currency;
amount.format = format;
console.log(amount.formatted);
You only have to set the options you want to set and it's easier to understand at a glance.
I was wondering, is there a better way of doing it though? Any tips?
Thanks!
Upvotes: 0
Views: 54
Reputation: 1601
I think it is better to pass the parameters as an Object,{value:val, currency:cur...}. and use a default configuration in the constructor to decrease the number of parameters to enter while using this class.
This is an example with one property you can do the same for the other properties
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€
Upvotes: 1