Back-end separation Calculator
I. Introduction
This task is based on the EE308 first work Visual Calculator to separate the front and back ends, save historical calculation results through interaction, and obtain the latest 10 results.
The Link Your Class | https://bbs.csdn.net/forums/ssynkqtd-04 |
---|---|
The Link of Requirement of This Assignment | https://bbs.csdn.net/topics/617378696 |
The Aim of This Assignment | Back-end separation calculator programming |
MU STU ID and FZU STU ID | MU ID 21126640 & FZU ID 832101104 |
Link to finished project code: https://github.com/SuJob1/Calculator/blob/main/
II. Link to the finished project code
https://github.com/SuJob1/Back-end-separation-calculator/tree/front-end
https://github.com/SuJob1/Back-end-separation-calculator/tree/back-end
III. PSP form
Personal Software Process Stages | Estimated Time(minutes) | Actual Time(minutes) |
---|---|---|
Planning | 30 | 45 |
• Estimate | 30 | 45 |
Development | 870 | 755 |
• Analysis | 60 | 70 |
• Design Spec | 40 | 30 |
• Design Review | 30 | 20 |
• Coding Standard | 20 | 15 |
• Design | 70 | 50 |
• Coding | 350 | 300 |
• Code Review | 100 | 70 |
• Test | 200 | 250 |
Reporting | 100 | 130 |
• Test Report | 50 | 85 |
• Size Measurement | 30 | 25 |
• Postmortem & Process Improvement Plan | 20 | 20 |
Sum | 1000 | 930 |
IV. Display of finished products
V. Design and Implementation Process
5.1. Design
5.1.1 Front-end
On the basis of realizing the function of the original calculator, I added the remainder %
, logarithm log
and exponential powere^
operation, and reformatted the whole button distribution. In addition, the historical query function is added, and a separate table is designed to store historical data on the right side of calculation.
5.1.2 Back-end
Since the function implementation of my front-end code is completed by JavaScript, I choose to use node.js as the back-end development platform and use the express framework for development. Considering that the contents stored in the calculator are relatively simple, I choose to use the lightweight database SQLite to store data.
5.2. Implementation
5.2.1 HTML Structure:
-
Form Structure: Add the table to store history data.
-
Input Elements: Add the button of remainder
%
, logarithmlog
, exponential powere^
and historyHistory
.
5.2.2 CSS Styling:
- Table: Design the color and position of the table.
5.2.3 JavaScript Logic:
- Calculation: Add new functions to calculate remainder
%
, logarithmlog
and exponential powere^
. - Interaction: (a) Add new functions saveCalculation to save the formula and results and send them to the server in the back end. (b) Obtain the results of the last 10 calculations from the server in the back end.
5.2.4 node.js:
- database Create and initialize the table format of the database.
- Save Get user revenue from the front end and save the results to the database.
- Obtain Return the result from the database to the front-end display.
5.3. Flow Chart:
VI. Code description
- Table design for history records
<table id="calculationsTable">
<thead>
<tr>
<th>formula</th>
<th>result</th>
</tr>
</thead>
<tbody>
<!-- Calculation history will be displayed here -->
</tbody>
</table>
This section creates the contents of the table.
/* Calculations table styling */
#calculationsTable {
position: absolute;
width: 300px;
margin-left: 600px;
margin-top: 100px;
border-collapse: collapse;
}
#calculationsTable th, #calculationsTable td {
padding: 8px;
border: 1px solid #ddd;
}
#calculationsTable th {
background-color: #f2f2f2;
color: black;
}
#calculationsTable tr:hover {
background-color: #ddd;
}
This section creates the style of the table such as color, font size, and placement.
- Operation of remainder, logarithm and exponential power
value = value.replace(/log(\d+)\((\d+)\)/g, function(match, base, number) {
return Math.log(number) / Math.log(base);
});
value = value.replace(/e\^(\d+)/g, function(match, exponent) {
return Math.pow(Math.E, Number(exponent));
});
value = value.replace(/(\d+)%(\d+)/g, function(match, firstValue, secondValue) {
return Number(firstValue) % Number(secondValue);
});
These 3 pieces of code are handling exponentials and logarithms and exponentials, converting them into actual numerical calculations, and replacing the results back into the original string.
- Front-end interaction
function saveCalculation(formula, result) {
fetch('http://localhost:3000/save', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ formula, result })
})
.then(response => response.json())
.then(data => {
if (!data.success) {
console.error('Error saving result:', data.error);
}
});
}
// New function: Get the results of the last 10 calculations
function fetchRecentCalculations() {
fetch('http://localhost:3000/recent')
.then(response => response.json())
.then(data => {
const tableBody = document.getElementById("calculationsTable").getElementsByTagName("tbody")[0];
tableBody.innerHTML = "";
data.forEach(calculation => {
const newRow = tableBody.insertRow();
newRow.insertCell(0).innerText = calculation.formula;
newRow.insertCell(1).innerText = calculation.result;
});
});
}
These two functions are used to obtain the Api interface of the back end and convert the data into Json format to pass to the back end to realize the writing and reading of the database.
- Back-end interaction
const express = require('express');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3');
const cors = require('cors');
const app = express();
app.use(cors());
const db = new sqlite3.Database('calculations.db');
app.use(bodyParser.json());
// Initialize the database
db.serialize(() => {
db.run("CREATE TABLE IF NOT EXISTS calculations (formula TEXT, result TEXT)");
});
// Save the calculation result to the database
app.post('/save', (req, res) => {
const formula = req.body.formula;
const result = req.body.result;
db.run("INSERT INTO calculations (formula, result) VALUES (?, ?)", [formula, result], (err) => {
if (err) {
return res.status(500).json({ error: err.message });
}
res.json({ success: true });
});
});
// Obtain the latest 10 calculation results
app.get('/recent', (req, res) => {
db.all("SELECT formula, result FROM calculations ORDER BY rowid DESC LIMIT 10", [], (err, rows) => {
if (err) {
return res.status(500).json({ error: err.message });
}
res.json(rows);
});
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
-
Importing Required Modules: The code uses the require statements to import modules like Express, Body Parser, SQLite3, and CORS.
-
Creating an Express App: An Express application is created using express(), and it initializes an SQLite3 database to store calculation history.
-
Setting Up CORS Middleware: The app.use(cors()) middleware is used to enable Cross-Origin Resource Sharing (CORS), allowing cross-domain requests.
-
Initializing Database Table: A table named “calculations” is created in the SQLite3 database to store the formula and result of calculations.
-
Defining an API Endpoint to Save Calculation Results: The code defines a POST request endpoint using app.post(‘/save’, …), which is used to save calculation results to the database.
-
Defining an API Endpoint to Retrieve Recent Calculation Results: A GET request endpoint is defined with app.get(‘/recent’, …), which retrieves the ten most recent calculation history records.
-
Starting the Server: The server is started using app.listen(PORT, …), and it listens on port 3000. The server address is displayed in the console.
VII. Summary
In this practice, I have learned a lot of back-end related knowledge and code writing, and I will use some simple databases to complete tasks through back-end interaction.