-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.ts
89 lines (75 loc) · 2.48 KB
/
service.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
import { availableOrgans, promotionScheme } from './config';
import { readCSV, validateOrders } from './utils';
import {
ProcessedResult,
Order,
Result,
CalculatedOrder,
} from './utils/interfaces';
import constants from './utils/stringConstants';
const calculateOrder = (order: Order): CalculatedOrder => {
const calculatedOrder: CalculatedOrder = {};
// Preparing result object model
availableOrgans.map((item) => {
calculatedOrder[item] = 0;
});
const organ = order.organ.toLowerCase();
const cash = Number(order.cash);
const price = Number(order.price);
const bonusRatio = Number(order.bonus_ratio);
// Calculating the number of organs purchased and bonuses
const purchased = Math.floor(cash / price);
const bonuseCounts = Math.floor(purchased / bonusRatio);
// Adding the purchased organs to the result object
calculatedOrder[organ] = purchased;
// Adding the bonus organs to the result object
if (bonuseCounts > 0 && organ in promotionScheme) {
const bonusOrgans = promotionScheme[organ].bonus;
for (const bonusOrgan in bonusOrgans) {
const bonusAmount = bonuseCounts * bonusOrgans[bonusOrgan];
calculatedOrder[bonusOrgan] += bonusAmount;
}
}
return calculatedOrder;
};
const formatOrder = (calculatedOrder: CalculatedOrder): string[] => {
const formattedResult: string[] = [];
for (const [key, value] of Object.entries(calculatedOrder)) {
formattedResult.push(`${key}: ${value}`);
}
return formattedResult;
};
export const processOrders = async (
orderFile: string
): Promise<ProcessedResult> => {
let processedResult: ProcessedResult;
const csvResult: Result = await readCSV(orderFile);
if (csvResult.success && csvResult.data) {
const finalResults: string[][] = [];
const isValidOrders = validateOrders(csvResult.data);
if (isValidOrders) {
for (const order of csvResult.data) {
// Calculating and applying the bonus
const calculatedOrder: CalculatedOrder = calculateOrder(order);
//Formatting the order w.r.t. output
const formattedResult: string[] = formatOrder(calculatedOrder);
finalResults.push(formattedResult);
}
processedResult = {
success: true,
data: finalResults,
};
} else {
processedResult = {
success: false,
message: constants.INVALID_ORDERS,
};
}
} else {
processedResult = {
success: false,
message: constants.INVALID_CSV,
};
}
return processedResult;
};