想知道是否有更好的方法来编写这个小块代码来记住DRY。我当然看到了功能上的相似之处,但我不确定如何缩短它。另外,我想知道缩短会产生多大差异。谢谢,杰森
var adminAlert = {
alert: function() {
var sumAlert = sumSupport = sumCashout = sumPhone = 0;
$.getJSON("alertFeed.JSON", function(data) {
$.each(data.alertData, function(i, allAlerts) {
sumAlert += parseFloat(allAlerts.value);
sumSupport += parseFloat(allAlerts.support);
sumCashout += parseFloat(allAlerts.cashout);
sumPhone += parseFloat(allAlerts.phone);
$(".alertPoints").html(sumAlert);
$(".support-requests").html(sumSupport);
$(".cashout-giftcards").html(sumCashout);
$(".phone-verification").html(sumPhone);
});
});
}
};
答案 0 :(得分:2)
版本底层更干。基本上,要使你的代码干,你:
parseFloat(allAlerts.foobar)
和$(".blablabla").html(foobar)
; allAlerts
对象中使用了一系列4个键:'value'
,'support'
,'cashout'
和'phone'
。这4个键中的每一个对应于CSS选择器,例如, cashout
对应".cashout-giftcards"
; {
'value': 'alertPoints',
'support': 'support-requests',
'cashout': 'cashout-giftcards',
'phone': 'phone-verification'
}
4。使用您在步骤3中创建的地图,将步骤1中标识的内容替换为更统一/抽象的代码。在您的情况下,sumCashout += parseFloat(allAlerts.cashout);
这四行只能替换为sum[k] = parseFloat(allAlerts[k])
< / p>
var
// To avoid repeatedly doing stuff like $(".alertPoints").html(sumAlert),
// we'll declare a concise map defining what will be updated by what:
map = {
'value': 'alertPoints', // later we will use this to update $(".alertPoints") with what comes from allAlerts.value
'support': 'support-requests', // later we will use this to update $(".support-requests") with what comes from allAlerts.support
'cashout': 'cashout-giftcards',
'phone': 'phone-verification'
},
adminAlert = {
alert: function(){
var
// Let's define an object that will hold the sums for us
sum = {},
// And also a variable to iterate our map;
k;
$.getJSON("alertFeed.JSON", function(data) {
$.each(data.alertData, function(i, allAlerts) {
// So we have 4 things to sum and update.
// They all are defined in our map.
// Lets go through the map and get things done:
for (k in map) {
// The value of k will be "value", "support" etc...
if (!(k in sum)) {
// In case the `sum` object does not yet have a key equal to the value of `k`, we initiate it.
// This is to have a start value of 0 to start adding to it:
sum[k] = 0;
}
// This is effectively the same as
// sumAlert += parseFloat(allAlerts.value) etc. etc.
// but written in unified manner to cover all the four cases.
// So when say `k` equals to `cashout`, this
// will be the same as `sum.cashout += parseFloat(allAlerts.cashout)`
sum[k] += parseFloat(allAlerts[k]);
// Again, a unified version of
// $(".alertPoints").html(sumAlert) etc. etc.
$('.' + map[k]).html(sum[k]);
}
});
});
}
};
就差异而言 - 维护/修复/调试/扩展等更容易。性能可能大致相同。