parking-calculator-library
Version:
A library to calculate parking fees based on duration, with discounts for early bird, weekend, and loyalty members.
79 lines (67 loc) • 2.47 kB
JavaScript
export class ParkingFeeCalculator {
constructor() {
this.rates = {
shortTerm: 10000, // Per hour for the first 2 hours (UGX)
midTerm: 7000, // Per hour for 2-6 hours (UGX)
longTerm: 5000, // Per hour after 6 hours (UGX)
dailyCap: 50000, // Maximum fee for 24 hours (UGX)
};
this.thresholds = {
shortTermLimit: 2, // Short-term duration limit in hours
midTermLimit: 6, // Mid-term duration limit in hours
};
}
calculateParkingDuration(entryTime, exitTime) {
if (!(entryTime instanceof Date) || !(exitTime instanceof Date)) {
throw new Error("Invalid timestamp input");
}
if (exitTime < entryTime) {
throw new Error("Exit time cannot be before entry time");
}
const durationMs = exitTime - entryTime;
return durationMs / (1000 * 60 * 60); // Convert milliseconds to hours
}
calculateParkingFee(entryTime, exitTime) {
const duration = this.calculateParkingDuration(entryTime, exitTime);
let totalFee = 0;
if (duration <= this.thresholds.shortTermLimit) {
totalFee = duration * this.rates.shortTerm;
} else if (duration <= this.thresholds.midTermLimit) {
totalFee =
this.thresholds.shortTermLimit * this.rates.shortTerm +
(duration - this.thresholds.shortTermLimit) * this.rates.midTerm;
} else {
totalFee = Math.min(
this.thresholds.shortTermLimit * this.rates.shortTerm +
(this.thresholds.midTermLimit - this.thresholds.shortTermLimit) *
this.rates.midTerm +
(duration - this.thresholds.midTermLimit) * this.rates.longTerm,
this.rates.dailyCap
);
}
return Number(totalFee.toFixed(2));
}
applyDiscounts(originalFee, options = {}) {
let discountedFee = originalFee;
let appliedDiscounts = [];
if (options.earlyBird && options.entryTime.getHours() < 9) {
discountedFee *= 0.8;
appliedDiscounts.push("Early Bird (20% off)");
}
if (
options.weekendDiscount &&
[0, 6].includes(options.entryTime.getDay())
) {
discountedFee *= 0.9;
appliedDiscounts.push("Weekend (10% off)");
}
if (options.loyaltyMember) {
discountedFee *= 0.95;
appliedDiscounts.push("Loyalty Member (5% off)");
}
return {
fee: Number(discountedFee.toFixed(2)),
discounts: appliedDiscounts,
};
}
}