Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reduce the total number of "break" and "continue" statements in this loop to use one at most in Javascript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 // 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.

>Solution :

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;
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading