Skip to content

Instantly share code, notes, and snippets.

@ismummy
Created February 19, 2023 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ismummy/d421ac3a982db27b4e8e51e9a734f271 to your computer and use it in GitHub Desktop.
Save ismummy/d421ac3a982db27b4e8e51e9a734f271 to your computer and use it in GitHub Desktop.
'use strict';
class Expense {
constructor(type, amount) {
this.type = type;
this.amount = amount;
}
}
class ExpenseReport {
constructor(expenses) {
this.expenses = expenses;
this.typeNames = {
1: "Breakfast",
2: "Lunch",
3: "Dinner"
};
}
getTotal() {
return this.expenses.reduce((acc, expense) => acc + expense.amount, 0);
}
getMealExpenses() {
return this.expenses.reduce((acc, expense) => {
if (expense.type === 1 || expense.type === 3) {
return acc + expense.amount;
}
return acc;
}, 0);
}
getTypeName(type) {
return this.typeNames[type];
}
getExpenseMarker(expense) {
if (
(expense.type === 3 && expense.amount > 100) ||
(expense.type === 2 && expense.amount > 50) ||
(expense.type === 1 && expense.amount > 20)
) {
return "[over-expense!]";
}
return " ";
}
printReport() {
console.info("Today Travel Expenses " + new Date().toISOString().slice(0, 10));
for (const expense of this.expenses) {
const expenseName = this.getTypeName(expense.type);
const expenseMarker = this.getExpenseMarker(expense);
console.info(expenseName + "\t" + expense.amount + "eur" + "\t" + expenseMarker);
}
console.info("Meal expenses: " + this.getMealExpenses() + "eur");
console.info("Total expenses: " + this.getTotal() + "eur");
}
}
// test cases
const expenses = [
new Expense(1, 15.20),
new Expense(1, 28.10),
new Expense(2, 10.20),
new Expense(3, 16.00),
new Expense(3, 120.20)
];
const report = new ExpenseReport(expenses);
console.log(report.getTotal() === 189.7);
console.log(report.getMealExpenses() === 159.3);
console.log(report.getTypeName(1) === "Breakfast");
console.log(report.getTypeName(2) === "Lunch");
console.log(report.getTypeName(3) === "Dinner");
console.log(report.getExpenseMarker(new Expense(3, 120.20)) === "[over-expense!]");
report.printReport();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment