1 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以重構(gòu)它以使用數(shù)組。然后,如果費(fèi)用發(fā)生變化,您無需修改代碼,只需更改該數(shù)組中的價(jià)格即可:
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");
添加回答
舉報(bào)