我正在构建一个基于WordPress的应用程序,客户端可以选择在过去几年中选择数据。我很想让这段代码变得更聪明,但我不知道该怎么做。 JS中的数据看起来像这样:
idsh: Array[4]
0: "565"
1: "565"
2: "567"
3: "569"
length: 4
datesh: Array[4]
0: "12/22/2014 - 00:00:00, 12:00 AM"
1: "01/21/2015 - 00:00:00, 12:00 AM"
2: "01/28/2015 - 00:00:00, 12:00 AM"
3: "02/04/2015 - 00:00:00, 12:00 AM"
length: 4
ids: Array[5]
0: "1009"
1: "979"
2: "1009"
3: "1011"
4: "1013"
length: 5
dates: Array[5]
0: "01/05/2015 - 00:00:00, 12:00 AM"
1: "12/22/2014 - 00:00:00, 12:00 AM"
2: "02/13/2015 - 00:00:00, 12:00 AM"
3: "02/20/2015 - 00:00:00, 12:00 AM"
4: "02/27/2015 - 00:00:00, 12:00 AM"
length: 5
var getQuarters = (function() {
'use strict';
var dates = [
"01/05/2015 - 00:00:00, 12:00 AM",
"12/22/2014 - 00:00:00, 12:00 AM",
"02/13/2015 - 00:00:00, 12:00 AM",
"02/20/2015 - 00:00:00, 12:00 AM",
"02/27/2015 - 00:00:00, 12:00 AM"
];
function loops(items, fn, onLoopComplete) {
var i;
try {
if (items && items.length) {
i = items.length;
} else {
throw new Error(items + ' is required to have a length');
}
if (i > -1) {
do {
if (items[i] !== undefined) {
fn(i);
/* console.log(i + ' is the current iteration'); */
}
}
while (--i >= 0);
}
if (typeof onLoopComplete === 'function') {
onLoopComplete(items.length);
}
} catch (e) {
throw new Error(e);
}
}
function show3() {
loops(dates, function(i) {
var months = dates[i].slice(0, 2),
thisMonth = new Date().getMonth();
if (months == thisMonth ||
months == thisMonth - 1 ||
months == thisMonth - 2) {
console.log(months);
} else {
console.log(dates[i] + ' do not meet criteria.');
}
});
}
function show6() {
loops(dates, function(i) {
var months = dates[i].slice(0, 2),
thisMonth = new Date().getMonth();
if (months == thisMonth ||
months == thisMonth - 1 ||
months == thisMonth - 2 ||
months == thisMonth - 3 ||
months == thisMonth - 4 ||
months == thisMonth - 5) {
console.log(months);
} else {
console.log(dates[i] + ' do not meet criteria.');
}
});
}
return function(quarters) {
switch (quarters) {
case 2:
show6();
break;
case 3:
show9();
break;
case 4:
show12();
break;
default:
show3();
break;
}
};
}());
getQuarters();
我遍历可用日期以查看它们是否符合条件(如过去3个月),但my code现在非常重复。我如何让它更聪明干爽?
答案 0 :(得分:1)
function showLastMonths(numberOfMonths){
loops(dates, function(i) {
var months = dates[i].slice(0, 2),
thisMonth = new Date().getMonth();
monthDifferential = thisMonth - months
if (monthDifferential > 0 && monthDifferential <= numberOfMonths ) {
console.log(months);
console.log(ids[i]);
} else {
console.log(dates[i] + ' do not meet criteria.');
}
});
}
这是我在那里看到的最简单的重构,只需提取参数并删除show3 show6等函数并调用它。