Skip to content

Instantly share code, notes, and snippets.

@jpjuliao
Last active February 9, 2023 14:46
Show Gist options
  • Save jpjuliao/5b89f765bb9fb9f44d5aac0edd74eb21 to your computer and use it in GitHub Desktop.
Save jpjuliao/5b89f765bb9fb9f44d5aac0edd74eb21 to your computer and use it in GitHub Desktop.
ExpressJS calculator via URL path
/**
* 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