Reputation: 12141
I'm building a simple ETL tool using Node.js. So, I get one json object and manipulate to another object. However, after running through Lint, I get
18:1 warning Function 'format' has a complexity of 5 complexity
This is the example of the code. I wish there's some JavaScript magic I could use.
if (rawObj.attr1 && rawObj.attr2) {
formattedObj.attr2 = rawObj.attr1;
}
if (rawObj.attr3) {
formattedObj.otherAttr = rawObj.attr3;
}
if (rawObj.attr4) {
formattedObj.otherAttr4 = rawObj.attr4;
}
formattedObj.rank = index + 1;
if (rawObj.attr5) {
formattedObj.otherAttr5 = rawObj.attr5;
}
basically, it's just checking if the property is undefined
or not. Then sets the property.
Upvotes: 0
Views: 914
Reputation: 664558
You're repeating yourself. Use a loop instead:
var props = [
{from: "attr3", to:"otherAttr"},
{from: "attr4", to:"otherAttr4"},
{from: "attr5", to:"otherAttr5"}
];
if (rawObj.attr2)
props.push({from: "attr1", to:"attr2"});
props.forEach(function(p) {
if (rawObj[p.from])
formattedObj[p.to] = rawObj[p.from];
});
formattedObj.rank = index + 1;
Upvotes: 2