When it comes to writing conditional statements in JS, there are various approaches you can take. If you have multiple statements, sticking to if
, else if
, and else
is usually recommended. However, there are other methods you can explore as well:
One option is to use the Ternary operator ? :
const {pr} = req.query
pr === 'trans'
? util.transUrl(req.originalUrl).then(param =>
res.redirect(param)
)
: pr === 'inst'
? util.instaUrl(req.originalUrl).then(param =>
res.redirect(param)
)
: res.status(400).send('Contact the editor of the originating page.')
Another approach is to utilize Gate logic && ||
const {pr} = req.query
(pr === 'trans' &&
util.transUrl(req.originalUrl).then(param =>
res.redirect(param))
) ||
(pr=== 'inst' &&
util.instaUrl(req.originalUrl).then(param =>
res.redirect(param))
) ||
res.status(400).send('Contact the editor of the originating page.')
Upon reviewing your code, it seems that your if and else if statements are quite similar. In such cases, you can eliminate else if
by utilizing the ternary operator efficiently like this:
const {pr} = req.query
if(pr === 'trans' || pr === 'inst'){
util[pr === 'trans' ? 'transUrl' : 'instaUrl'](req.originalUrl)
.then(param => res.redirect(param))
}
else{
res.status(400).send('Contact the editor of the originating page.')
}
Just a quick tip: It's always advisable to use ===
instead of ==
when comparing strings to avoid coercion.