Sure! Let's build a Cash Register application step by step. We'll create three files: index.html, style.css, and script.js. Here's an overview of what we'll do:
- HTML (
index.html): Set up the structure of the app with input fields, buttons, and display areas.
- CSS (
style.css): Style the application to make it user-friendly and visually appealing.
- JavaScript (
script.js): Implement the logic to calculate change, handle different scenarios, and display appropriate messages.
Let's dive into each part.
1. HTML (index.html)
We'll create a simple layout with:
- An input field for the user to enter the cash provided.
- A button to trigger the purchase.
- A display area to show the change due or status messages.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cash Register App</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Cash Register</h1>
<div class="input-group">
<label for="price">Item Price ($):</label>
<input type="number" id="price" step="0.01" value="19.5">
</div>
<div class="input-group">
<label for="cash">Cash Provided ($):</label>
<input type="number" id="cash" step="0.01">
</div>
<button id="purchase-btn">Purchase</button>
<div id="change-due" class="change-due"></div>
</div>
<script src="script.js"></script>
</body>
</html>
Explanation:
<input id="price">: Allows setting the price of the item. Pre-filled with 19.5 for testing.
<input id="cash">: User enters the cash provided.
<button id="purchase-btn">: Triggers the purchase process.
<div id="change-due">: Displays the change or status messages.
2. CSS (style.css)
We'll style the application to make it clean and user-friendly.
* {
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
padding: 20px;
}
.container {
max-width: 400px;
margin: auto;
background: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
color: #333;
}
.input-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
color: #555;
}
input[type="number"] {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
#purchase-btn {
width: 100%;
padding: 12px;
background-color: #28a745;
border: none;
color: white;
font-size: 16px;
border-radius: 4px;
cursor: pointer;
}
#purchase-btn:hover {
background-color: #218838;
}
.change-due {
margin-top: 20px;
padding: 15px;
background-color: #e9ecef;
border-radius: 4px;
min-height: 50px;
color: #333;
}
Explanation:
- Styling: Provides a clean layout with responsive input fields and buttons.
- Container: Centers the app with padding and a subtle shadow.
- Button Hover Effect: Enhances user experience by changing the button color on hover.
3. JavaScript (script.js)
This is the core of the application. We'll implement the logic to calculate change, handle different scenarios, and update the DOM accordingly.
// Define currency units and their values
const UNIT_AMOUNT = [
{ name: "ONE HUNDRED", val: 100.0 },
{ name: "TWENTY", val: 20.0 },
{ name: "TEN", val: 10.0 },
{ name: "FIVE", val: 5.0 },
{ name: "ONE", val: 1.0 },
{ name: "QUARTER", val: 0.25 },
{ name: "DIME", val: 0.1 },
{ name: "NICKEL", val: 0.05 },
{ name: "PENNY", val: 0.01 }
];
// Initialize variables
let price = parseFloat(document.getElementById('price').value);
let cash;
let cid = [
["PENNY", 1.01],
["NICKEL", 2.05],
["DIME", 3.1],
["QUARTER", 4.25],
["ONE", 90],
["FIVE", 55],
["TEN", 20],
["TWENTY", 60],
["ONE HUNDRED", 100]
];
// Function to update 'price' when input changes
document.getElementById('price').addEventListener('input', function() {
price = parseFloat(this.value);
});
// Function to handle purchase
document.getElementById('purchase-btn').addEventListener('click', function() {
cash = parseFloat(document.getElementById('cash').value);
// Call checkCashRegister and display result
const result = checkCashRegister(price, cash, cid);
displayResult(result);
});
// Function to display the result in the DOM
function displayResult(result) {
const changeDueElement = document.getElementById('change-due');
if (result.status === "INSUFFICIENT_FUNDS" || result.status === "CLOSED") {
changeDueElement.textContent = `Status: ${result.status}`;
if (result.status === "CLOSED") {
changeDueElement.textContent += " " + formatCid(result.change);
}
} else if (result.status === "OPEN") {
let changeString = "Status: OPEN ";
changeString += formatChange(result.change);
changeDueElement.textContent = changeString;
}
}
// Helper function to format the change array into desired string
function formatChange(change) {
return change.map(currency => `${currency.name}: $${currency.amount}`).join(' ');
}
// Helper function to format CID for CLOSED status
function formatCid(change) {
return change.map(currency => `${currency.name}: $${currency.amount}`).join(' ');
}
// Main function to check cash register
function checkCashRegister(price, cash, cid) {
let changeDue = (cash - price).toFixed(2);
let totalCid = cid.reduce((sum, curr) => sum + curr[1], 0).toFixed(2);
// Convert cid to an object
let register = cid.reduce((acc, curr) => {
acc[curr[0]] = curr[1];
return acc;
}, {});
// If cash provided is less than price
if (cash < price) {
alert("Customer does not have enough money to purchase the item");
return { status: "INSUFFICIENT_FUNDS", change: [] };
}
// If cash provided equals price
if (cash === price) {
document.getElementById('change-due').textContent = "No change due - customer paid with exact cash";
return { status: "CLOSED", change: cid };
}
// If cash in drawer is less than change due
if (totalCid < changeDue) {
return { status: "INSUFFICIENT_FUNDS", change: [] };
}
// If cash in drawer equals change due
if (totalCid === changeDue) {
return { status: "CLOSED", change: cid };
}
// Calculate change
let changeArray = [];
for (let unit of UNIT_AMOUNT) {
let amount = 0;
while (changeDue >= unit.val && register[unit.name] > 0) {
changeDue -= unit.val;
changeDue = Math.round(changeDue * 100) / 100; // Avoid floating point issues
register[unit.name] -= unit.val;
amount += unit.val;
}
if (amount > 0) {
changeArray.push({ name: unit.name, amount: amount.toFixed(2) });
}
}
// Check if exact change was given
let remaining = changeArray.reduce((sum, curr) => sum + parseFloat(curr.amount), 0).toFixed(2);
if (remaining != (cash - price).toFixed(2)) {
return { status: "INSUFFICIENT_FUNDS", change: [] };
}
return { status: "OPEN", change: changeArray };
}
Explanation:
-
Currency Units:
- Defined in
UNIT_AMOUNT array from highest to lowest to facilitate giving change with the largest denominations first.
-
Variable Initialization:
price: The price of the item, taken from the input field.
cash: The cash provided by the customer, taken from the input field when the purchase button is clicked.
cid: Cash-in-drawer, initialized with given values. You can modify this array for different test cases.
-
Event Listeners:
- Price Input Change: Updates the
price variable whenever the user changes the price input.
- Purchase Button Click: When clicked, it reads the cash input, calls the
checkCashRegister function, and displays the result.
-
checkCashRegister Function:
- Calculate Change Due:
cash - price.
- Total CID: Sum of all the money in the cash drawer.
- Various Scenarios:
- Insufficient Cash Provided: Alerts the user if the cash provided is less than the price.
- Exact Cash Provided: Informs no change is due.
- Insufficient Funds in Drawer: If total CID is less than change due.
- Exact Change in Drawer: If total CID equals change due.
- Open Drawer: Calculates change using the highest denominations first. If exact change can't be made, returns insufficient funds.
-
Helper Functions:
displayResult: Updates the DOM based on the result.
formatChange: Formats the change array into a readable string.
formatCid: Formats the entire CID when drawer status is closed.
-
Handling Floating Point Precision:
- Used
toFixed(2) and Math.round to avoid issues with floating-point arithmetic (e.g., 0.1 + 0.2 not exactly equaling 0.3).
Testing the Application
Let's go through the user stories and ensure our application handles all scenarios.
1. Customer Provides Less Cash Than Price
- Price: Any (e.g.,
$19.5)
- Cash: Less than
$19.5 (e.g., $10)
- Expected Result: Alert "Customer does not have enough money to purchase the item"
Test:
Enter $19.5 for price and $10 for cash, then click "Purchase". An alert should appear.
2. Customer Provides Exact Cash
- Price:
$19.5
- Cash:
$19.5
- Expected Result: "No change due - customer paid with exact cash"
Test:
Enter $19.5 for price and $19.5 for cash, then click "Purchase". The message should display accordingly.
3. Customer Needs Change and Drawer Has Enough Funds
Test 1:
- Price:
$19.5
- Cash:
$20
- CID:
[
["PENNY", 1.01],
["NICKEL", 2.05],
["DIME", 3.1],
["QUARTER", 4.25],
["ONE", 90],
["FIVE", 55],
["TEN", 20],
["TWENTY", 60],
["ONE HUNDRED", 100]
]
- Expected Result:
Status: OPEN QUARTER: $0.5
Test 2:
- Price:
$3.26
- Cash:
$100
- CID: Same as above
- Expected Result:
Status: OPEN TWENTY: $60 TEN: $20 FIVE: $15 ONE: $1 QUARTER: $0.5 DIME: $0.2 PENNY: $0.04
Test:
Adjust the price and cash accordingly and click "Purchase". The change due should be displayed as expected.
4. Drawer Does Not Have Enough Funds for Exact Change
Test 1:
- Price:
$19.5
- Cash:
$20
- CID:
[
["PENNY", 0.01],
["NICKEL", 0],
["DIME", 0],
["QUARTER", 0],
["ONE", 0],
["FIVE", 0],
["TEN", 0],
["TWENTY", 0],
["ONE HUNDRED", 0]
]
- Expected Result:
Status: INSUFFICIENT_FUNDS
Test 2:
- Price:
$19.5
- Cash:
$20
- CID:
[
["PENNY", 0.01],
["NICKEL", 0],
["DIME", 0],
["QUARTER", 0],
["ONE", 1],
["FIVE", 0],
["TEN", 0],
["TWENTY", 0],
["ONE HUNDRED", 0]
]
- Expected Result:
Status: INSUFFICIENT_FUNDS
Test 3:
- Price:
$19.5
- Cash:
$20
- CID:
[
["PENNY", 0.5],
["NICKEL", 0],
["DIME", 0],
["QUARTER", 0],
["ONE", 0],
["FIVE", 0],
["TEN", 0],
["TWENTY", 0],
["ONE HUNDRED", 0]
]
- Expected Result:
Status: CLOSED PENNY: $0.5
Test:
Again, adjust the CID accordingly and verify the results.
Final Thoughts
This implementation covers all the specified user stories and scenarios. You can further enhance the application by:
- Dynamic CID Input: Allow users to input the cash in the drawer dynamically.
- Error Handling: Improve validations for user inputs.
- Detailed Breakdown: Provide a more detailed breakdown of change denominations.
Feel free to customize the styles in style.css to match your personal preference. Happy Coding!