In your **Expense Tracker System**, the key part of the program that utilizes a
**data structure** (Array) and **algorithms** (sorting, adding, deleting) is in the
**handling of expenses**. Here's how the data structure and algorithms are applied
in your program:
### 1. **Data Structure: Array**
In your program, the primary data structure used to store and manage expenses is an
**array**. This array stores each expense as an object, where each object consists
of an expense title and its corresponding amount.
- **Expenses Array**: This array is stored in the `localStorage` so that the
expenses persist even after the page is reloaded. Whenever a new expense is added
or an expense is deleted, this array is updated, and the new state is saved back
into `localStorage`.
Here’s the relevant part of your JavaScript where the array is used:
```javascript
let expenses = JSON.parse(localStorage.getItem("expenses")) || [];
```
This line fetches the expenses array from the browser's `localStorage`, or
initializes it as an empty array if no expenses have been saved yet.
### 2. **Algorithm: Adding Expenses**
When a user adds a new expense, the following algorithm is executed:
- **Step 1**: Retrieve the expense details (title and amount) from the input
fields.
- **Step 2**: Create a new expense object with the entered data.
- **Step 3**: Push the new expense object into the expenses array.
- **Step 4**: Save the updated array back to `localStorage`.
- **Step 5**: Update the displayed list of expenses in the table.
Here’s the relevant part of the code for adding an expense:
```javascript
document.querySelector(".add-expense-container form").addEventListener("submit",
function(event) {
event.preventDefault();
let expenseTitle = document.getElementById("expense").value;
let expenseAmount = document.getElementById("amount").value;
if (expenseTitle && expenseAmount) {
let expense = {
title: expenseTitle,
amount: parseFloat(expenseAmount)
};
let expenses = JSON.parse(localStorage.getItem("expenses")) || [];
expenses.push(expense); // Add new expense to the array
localStorage.setItem("expenses", JSON.stringify(expenses)); // Save
updated expenses
updateHistory(expenses); // Update the displayed list
document.getElementById("expense").value = "";
document.getElementById("amount").value = "";
} else {
alert("Please provide both title and amount.");
}
});
```
### 3. **Algorithm: Deleting Expenses**
When an expense is deleted, the following algorithm is executed:
- **Step 1**: Identify the expense to delete, based on its title.
- **Step 2**: Filter out the expense from the array (using a filter function).
- **Step 3**: Save the updated array back to `localStorage`.
- **Step 4**: Update the displayed list of expenses.
Here’s the relevant part of the code for deleting an expense:
```javascript
function deleteExpense(expenseTitle) {
let expenses = JSON.parse(localStorage.getItem("expenses"));
expenses = expenses.filter(expense => expense.title !== expenseTitle); //
Remove expense by title
localStorage.setItem("expenses", JSON.stringify(expenses)); // Save updated
expenses
updateHistory(expenses); // Update the displayed list
}
```
### 4. **Algorithm: Sorting Expenses**
The algorithm to **sort** expenses is executed when the user clicks the "Sort
Expenses" button. The steps of this algorithm are:
- **Step 1**: Fetch the current array of expenses from `localStorage`.
- **Step 2**: Sort the array in ascending or descending order based on the expense
amount.
- **Step 3**: Update the displayed list of expenses after sorting.
Here’s the relevant part of the code for sorting expenses:
```javascript
document.querySelector(".sort-expenses-btn").addEventListener("click", function() {
let sortOrder = this.getAttribute("data-sort-order");
let expenses = JSON.parse(localStorage.getItem("expenses"));
if (sortOrder === "asc") {
expenses.sort((a, b) => a.amount - b.amount); // Sort in ascending order
this.setAttribute("data-sort-order", "desc");
this.textContent = "Sort Expenses (Descending)";
} else {
expenses.sort((a, b) => b.amount - a.amount); // Sort in descending order
this.setAttribute("data-sort-order", "asc");
this.textContent = "Sort Expenses (Ascending)";
}
localStorage.setItem("expenses", JSON.stringify(expenses)); // Save updated
expenses
updateHistory(expenses); // Update the displayed list
});
```
### **Key Data Structures and Algorithms Used:**
1. **Data Structure: Array**
- The `expenses` array holds all the expense records as objects.
- Operations on the array:
- **Adding an expense**: `push()`
- **Deleting an expense**: `filter()`
- **Sorting expenses**: `sort()`
2. **Algorithm: Sorting**
- Sorting is performed using the built-in JavaScript `sort()` method, which is
an example of an **in-place sorting algorithm**.
- **Time Complexity**: The `sort()` function generally uses an algorithm like
**QuickSort** or **MergeSort**, with an average time complexity of O(n log n).
3. **Algorithm: Filtering**
- **Deleting an expense** is done using the `filter()` method, which removes all
expenses that do not match the title of the expense to be deleted.
- **Time Complexity**: The `filter()` method is O(n), where n is the number of
expenses in the array.
4. **Algorithm: Adding/Removing Items**
- When adding a new expense, the `push()` method is used, which has a time
complexity of O(1).
- When removing an expense (filtering), the time complexity is O(n), as it needs
to iterate through the array to check each expense.
### Conclusion:
- **Array** is used as the core **data structure** to store expenses, allowing for
dynamic operations like adding, deleting, and sorting.
- **Algorithms** are employed for sorting expenses, adding new items, and deleting
them based on certain criteria. Specifically, the **sorting algorithm** and
**filtering algorithm** are central to modifying the expense list in the program.