I am refactoring code written by another developer. On SonarQube, the error thrown is that I need to "Reduce the total number of "break" and "continue" statements in this loop to use one at most".
I'm trying to refactor the code so that it logically makes sense but without the use of continue. As a problem solver, what's the best approach to refactor the code and still maintain the same logic?
See sample code below.
// once we reach the first item that was created before the user's itemUpdatedAt,
// we know that the user has accepted that item
const userReport = (user, items) => {
for (const item of items) {
if (user.itemUpdatedAt < item.createdAt) {
continue;
}
reportItem['Accepted date'] = intl.format(
new Date(user.itemUpdatedAt)
);
reportItem['Version accepted'] = item
? intl.format(new Date(item.createdAt))
: null;
break;
}
return reportItem;
}
I have tried to add the break code where the continue statement is and reverse the if logic. But I'm uncertain that it produces the same logic that needs to be achieved.
CodePudding user response:
Per Pointy's comment, you can use Array#find
to determine if any of the items have been "accepted".
const setAcceptanceMetadata = (reportItem, user, items) => {
const firstAcceptedItem = items.find((item) =>
user.itemUpdatedAt >= item.createdAt)
if(firstAcceptedItem) {
reportItem['Accepted date'] =
intl.format(new Date(user.itemUpdatedAt));
reportItem['Version accepted'] =
item ? intl.format(new Date(item.createdAt)) : null;
}
return reportItem;
}