-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathprices_typed.ts
102 lines (89 loc) · 2.71 KB
/
prices_typed.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import "./polyfills";
import express from "express";
import { Database } from "./database";
// Refactor the following code to get rid of the legacy Date class.
// Use Temporal.PlainDate instead. See /test/date_conversion.spec.mjs for examples.
function createApp(database: Database) {
const app = express();
app.put("/prices", (req, res) => {
const type = req.query.type as string;
const cost = parseInt(req.query.cost as string);
database.setBasePrice(type, cost);
res.json();
});
app.get("/prices", (req, res) => {
const age = req.query.age ? parseInt(req.query.age as string) : undefined;
const type = req.query.type as string;
const baseCost = database.findBasePriceByType(type)!.cost;
const date = parseDate(req.query.date as string);
const cost = calculateCost(age, type, date, baseCost);
res.json({ cost });
});
function parseDate(dateString: string | undefined): Date | undefined {
if (dateString) {
return new Date(dateString);
}
}
function calculateCost(age: number | undefined, type: string, date: Date | undefined, baseCost: number) {
if (type === "night") {
return calculateCostForNightTicket(age, baseCost);
} else {
return calculateCostForDayTicket(age, date, baseCost);
}
}
function calculateCostForNightTicket(age: number | undefined, baseCost: number) {
if (age === undefined) {
return 0;
}
if (age < 6) {
return 0;
}
if (age > 64) {
return Math.ceil(baseCost * 0.4);
}
return baseCost;
}
function calculateCostForDayTicket(age: number | undefined, date: Date | undefined, baseCost: number) {
let reduction = calculateReduction(date);
if (age === undefined) {
return Math.ceil(baseCost * (1 - reduction / 100));
}
if (age < 6) {
return 0;
}
if (age < 15) {
return Math.ceil(baseCost * 0.7);
}
if (age > 64) {
return Math.ceil(baseCost * 0.75 * (1 - reduction / 100));
}
return Math.ceil(baseCost * (1 - reduction / 100));
}
function calculateReduction(date: Date | undefined) {
let reduction = 0;
if (date && isMonday(date) && !isHoliday(date)) {
reduction = 35;
}
return reduction;
}
function isMonday(date: Date) {
return date.getDay() === 1;
}
function isHoliday(date: Date | undefined) {
const holidays = database.getHolidays();
for (let row of holidays) {
let holiday = new Date(row.holiday);
if (
date &&
date.getFullYear() === holiday.getFullYear() &&
date.getMonth() === holiday.getMonth() &&
date.getDate() === holiday.getDate()
) {
return true;
}
}
return false;
}
return app;
}
export { createApp };