我正在以角度js创建自定义货币过滤器。一切正常,但我想看看是否有更简单的方法来简化我的一些代码。
这是我通过过滤器的地方。
<p>{{ 44.95 | formatCurrency }}</p>
理想情况下,我会从api获得市场,但现在我只是嘲笑它:
.filter('formatCurrency', function(currencyService){
//from api call
let market = 'Br';
return function(number) {
const marketFormat = currencyService.get(market);
let output;
number = number.toString().replace('.', marketFormat.decimalDelimiter);
addCurrencySymbol(number);
function addCurrencySymbol(number){
const symbol = marketFormat.currencySign;
number = marketFormat.showsBefore ? symbol + number : number + symbol;
addSpecialString(number);
}
function addSpecialString(number){
const specialString = marketFormat.specialString;
if (specialString) {
number = marketFormat.showsStringBefore ? specialString + ' ' + number : number + ' ' + specialString;
}
output = number
}
return output;
}
});
我使用名为currencyService的服务来获取市场喜欢过滤货币的方式的数据属性:
.service('currencyService', function(){
function get(market){
let numberFormatForMarket = {
US: { decimalDelimiter: '.', currencySign: '$', showsBefore: true, specialString: null },
UK: { decimalDelimiter: '.', currencySign: '£', showsBefore: true, specialString: null },
FR: { decimalDelimiter: ',', currencySign: '€', showsBefore: false, specialString: null },
ES: { decimalDelimiter: ',', currencySign: '€', showsBefore: false, specialString: null },
BEnl: { decimalDelimiter: ',', currencySign: '€', showsBefore: false, specialString: null },
BEfr: { decimalDelimiter: ',', currencySign: '€', showsBefore: false, specialString: null },
CAen: { decimalDelimiter: '.', currencySign: '$', showsBefore: false, specialString: 'C', showsStringBefore: true },
CAfr: { decimalDelimiter: ',', currencySign: '$', showsBefore: false, specialString: 'C', showsStringBefore: false },
SE: { decimalDelimiter: '.', currencySign: '', showsBefore: false, specialString: 'kr', showsStringBefore: false },
AU: { decimalDelimiter: '.', currencySign: '$', showsBefore: true, specialString: 'A', showsStringBefore: true },
NZ: { decimalDelimiter: '.', currencySign: '$', showsBefore: true, specialString: 'NZ', showsStringBefore: true },
DE: { decimalDelimiter: ',', currencySign: '€', showsBefore: false, specialString: null },
NL: { decimalDelimiter: ',', currencySign: '€', showsBefore: false, specialString: null },
CHfr: { decimalDelimiter: '.', currencySign: '', showsBefore: true, specialString: 'Fr.', showsStringBefore: true },
CHde: { decimalDelimiter: '.', currencySign: '', showsBefore: true, specialString: 'Fr.', showsStringBefore: true },
Br: { decimalDelimiter: ',', currencySign: '$', showsBefore: true, specialString: 'R', showsStringBefore: true },
}
return numberFormatForMarket[market];
}
return {
get
}
以下是代码:https://embed.plnkr.co/GJELOhMSECxXpCm9J3V9/ 我的主要问题是:我正努力尝试编写CLEAN CODE。我能在这里做些什么来简化事情吗?