Last active
February 9, 2023 14:46
-
-
Save jpjuliao/5b89f765bb9fb9f44d5aac0edd74eb21 to your computer and use it in GitHub Desktop.
ExpressJS calculator via URL path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This script serves a simple calculator app which get the input from the URL path. | |
* | |
* URL Format: http://locahost/:{port}/{number1}{math operator(+, -, * or /)}/{number2} | |
* Example: http://localhost:3333/23+40 | |
*/ | |
const express = require('express') | |
const app = express() | |
const port = 3333 | |
app.all('*', (req, res) => { | |
const path = req.originalUrl.slice(-1) === '/' | |
? req.originalUrl.slice(1).substring(1) : req.originalUrl.slice(1) | |
const operations = { | |
'+': (a, b) => a + b, | |
'-': (a, b) => a - b, | |
'*': (a, b) => a * b, | |
'/': (a, b) => a / b, | |
} | |
for (const operator in operations) { | |
if (path.indexOf(operator) === -1) continue | |
const numbers = path.split(operator).map(n => Number(n)) | |
const result = numbers.reduce((acc, curr) => { | |
return operations[operator](acc, curr) | |
} | |
) | |
res.json({ result: result, numbers: numbers, operator: operator }) | |
break | |
} | |
res.json({ result: "Error" }) | |
}) | |
app.listen(port, () => { | |
console.log(`listening on port http://localhost:${port}/`) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment