1 回答
TA贡献1796条经验 获得超4个赞
您可以重构它以使用数组。然后,如果费用发生变化,您无需修改代码,只需更改该数组中的价格即可:
const steps = [
{ limit: 20, fee: 2 }, // The limits are in minutes
{ limit: 40, fee: 4 },
{ limit: 60, fee: 6 },
{ limit: 2 * 60, fee: 7 },
{ limit: 3 * 60, fee: 9 },
{ limit: 4 * 60, fee: 11 },
{ limit: 8 * 60, fee: 13 },
{ limit: 24 * 60, fee: 15 }, // For complex rules, use a function:
{ limit: Infinity, fee: minutes => 9 * Math.ceil(minutes / 24 / 60) + 7 }
];
// Converts a date string to a number of minutes since 1970-01-01
const dateToMinutes = str => Math.floor(new Date(str).getTime() / 60000);
const calcFee = (parkingDate, returnDate) => {
const minutesParked = dateToMinutes(returnDate) - dateToMinutes(parkingDate);
for (let step of steps) {
if (minutesParked <= step.limit) {
return isNaN(step.fee) ? step.fee(minutesParked) : step.fee;
}
}
};
// Just for testing
const test = (x, y) => (document.body.innerHTML += `<p>${x} - ${y}<br><b>${formatDuration(x, y)}: €${calcFee(x, y)}</b></p>`); const formatDuration = (x, y) => { const d = dateToMinutes(y) - dateToMinutes(x); const res = {d: Math.floor(d / 24 / 60), h: Math.floor((d % (24 * 60)) / 60), m: d % 60}; return `${res.d} days ${res.h} hours ${res.m} min`; };
test("2020-05-12 18:30:00", "2020-05-12 18:40:00");
test("2020-05-12 18:30:00", "2020-05-12 19:00:00");
test("2020-05-12 18:30:00", "2020-05-12 19:30:00");
test("2020-05-12 18:30:00", "2020-05-13 18:29:00");
test("2020-05-12 18:30:00", "2020-05-13 18:31:00");
test("2020-05-12 18:30:00", "2020-05-18 18:30:00");
添加回答
举报