'How can I solve below requirement in node js?
As I'm new to node js for practice I want to try out some problems on hacker rank. I was able solve most of the problems, but I got stuck at this problem.
I don't have an idea how to route this kind of query string node js/
The question is to create a simple calculator app with the following requirements.
/cal?func=add&a=20&b=25 -> Get method
-> this route should add value of "a" and "b".Expected response: Addition is 45
/cal?func=subtract&a=25&b=20 -> Get method
-> this route should subtract value of "a" and "b".Expected response: Addition is 5
Problem requirements:
Solution 1:[1]
Simple way to do it if you're using expressJS, you just need to get the query values and do your calculation, you can do multiple if to know which function to execute or you can do it with a map of function. Here I used a variable funcMap that hold property add, sub, mul :
const funcMap = {
add: (a, b) => a + b,
sub: (a, b) => a - b,
mul: (a, b) => a * b
}
// using ExpressJS
router.get('/cal', (req,res) => {
const { func, a, b } = req.query;
// you should check if func exist and is valid, same for a and b.
res.send(funcMap[func](+a, +b));
});
// using NodeJS
const url = require('url');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
if (req.url === '/cal') {
const { func, a, b } = url.parse(req.url, true).query;
res.write(funcMap[func](+a, +b));
}
res.end();
})
Solution 2:[2]
Create Route like this,
const express = require('express')
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))
const router = express.Router()
router.route('/cal').get(testController.cal());
then you need to create a controller and put the function there.
async cal(req, res) {
let a = req.query.a;
let b = req.query.b;
if(req.query.func == 'add'){
return ( a + b );
}
else {
return true;
}
}
Solution 3:[3]
use the query parameters to get the values from incoming request
exports.calculate=(req,res,next)=>{
const {a,b,func}=req.query;
let result;
if(func=="add"){
result=parseInt(a)+parseInt(b);
}
else if(func=="subtract"){
result=parseInt(a)-parseInt(b);
}
else{
result="Invalid function";
}
return result;
}
Solution 4:[4]
const http = require("http");
const url = require("url");
const funcMap = {
add: (a, b) => {
return `Addition is: ${a + b}`;
},
subtract: (a, b) => {
return `Subtraction is: ${a - b}`;
},
multiple: (a, b) => {
return `Multiplication is: ${a * b}`;
},
div: (a, b) => {
return `Division is: ${a / b}`;
},
};
http.createServer((req, response) => {
response.writeHead(200, {
"Content-Type": "text/html"
});
req.setEncoding("utf-8");
let urlhandler = url.parse(req.url, true);
let pathname = urlhandler.pathname;
let {
func,
a,
b
} = urlhandler.query;
if (pathname === "/cal") {
if (func == undefined) {
response.write(funcMap["div"](+a, +b));
} else {
response.write(funcMap[func](+a, +b));
}
}
response.end();
})
.listen(8000);
Solution 5:[5]
Best solution is use object:
const express = require("express");
const app = express();
const port = 5000;
app.listen(port, () => console.log(`the server run on port --> : ${port}`));
app.get("/operate/:option/:op1/:op2", (req, res) => {
const { option, op1, op2 } = req.params;
const result = {
mul: op1 * op2,
add: parseInt(op1) + parseInt(op2),
sub: op1 - op2,
div: op1 / op2,
};
res.json({ message: option, result: result[option] });
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | Hemant Modi |
Solution 4 | Dheeraj bisht |
Solution 5 | Tyler2P |