patternjavascriptMinor
Functions that return a variable
Viewed 0 times
returnfunctionsvariablethat
Problem
I'm simple looking for what the general preference is between the below options:
-
anon function directly to variable
-
raw build variable up
-
complete separation
-
anon function directly to variable
middleware.customer = function(req, res, next){
req.customer = function(){
var customer = false;
if(req.method == "POST") customer = req.body;
if(req.method == "GET") customer = req.query;
return customer;
}();
return next();
}-
raw build variable up
middleware.customer = function(req, res, next){
req.customer = false;
if(req.method == "POST") req.customer = req.body;
if(req.method == "GET") req.customer = req.query;
return next();
}-
complete separation
var customer = function(req){
var customer = false;
if(req.method == "POST") customer = req.body;
if(req.method == "GET") customer = req.query;
return customer;
}
middleware.customer = function(req, res, next){
req.customer = customer(req);
return next();
}Solution
I think B is the best of the three, but here's another alternative using a simple lookup:
middleware.customer = function(req, res, next){
var methods = {POST: req.body, GET: req.query};
req.customer = methods[req.method] || false;
return next();
}Code Snippets
middleware.customer = function(req, res, next){
var methods = {POST: req.body, GET: req.query};
req.customer = methods[req.method] || false;
return next();
}Context
StackExchange Code Review Q#39568, answer score: 9
Revisions (0)
No revisions yet.