I came across this code on a legacy project I am trying to clean and get lean.
I have a multiple if conditions where the structure is essentially the same:
async function _validateRenderRequestById({
id: requestId,
user = null,
uploadToCampaign = false,
requestGroups = null,
}) {
const request = await getRequestTasksById(requestId);
if (!request) return null;
let validated = false;
const payload = { request, user, uploadToCampaign };
if (request.type === requestTypes.r && request.RequestTasks.length) {
validated = await _validateRequest({ ...payload, renderGroups });
}
if (request.type === requestTypes.a && request.ARequestTasks.length) {
validated = await _validateARequest({ ...payload, renderGroups });
}
if (request.type === requestTypes.e && request.ERequestTasks.length) {
validated = await _validateERequest(payload);
}
if (request.type === requestTypes.s && request.SRequestTasks.length) {
validated = await _validateSRequest(payload);
}
...
}
CodePudding user response:
I'm not entirely sure this is worth changing, but if you want to make it table-driven, you can do so like this by defining a table that you can look up the requestType and then fetch the property name of the array you're checking the .length
on and the matching validation function reference:
const requestMap = {
[requestTypes.r]: {name: "RequestTasks", fn: _validateRequest},
[requestTypes.a]: {name: "ARequestTasks", fn: _validateARequest},
[requestTypes.e]: {name: "ERequestTasks", fn: _validateERequest},
[requestTypes.s]: {name: "SRequestTasks", fn: _validateSRequest},
};
async function _validateRenderRequestById({
id: requestId,
user = null,
uploadToCampaign = false,
requestGroups = null,
}) {
const request = await getRequestTasksById(requestId);
if (!request) return null;
let validated = false;
const payload = {
request,
user,
uploadToCampaign
};
let requestInfo = requestMap[request.type];
if (requestInfo && request[requestInfo.name].length) {
validated = await requestInfo.fn({
...payload,
renderGroups
});
}
...
}