Deep Duggal
Deep Duggal

Reputation: 15

Is there a better way to do this? Reusing the same loop in multiple functions?

These 3 functions use the same loop separately.

Should I remove the loops from each function and put them in one large loop? Is there some other better way?

    function createArrayOfNames(catsArray) {
        var catNames = [];
        for (var i = 0; i<catsArrayLength; i++) {
            catNames.push(cats[i].name);
        }
        return catNames;
    }

    //
    function createArrayOfListElements(listElement, catNames) {
        for(i = 0; i<catsArrayLength; i++) {
            var listElements = [];
            var listElement = listElement;
            listElement.innerHTML = catNames[i]
            listElements.append(listElement);
        }
        return listElements;
    }

    //Adds cat names to the catList unordered list (inside the catListContainer div)
    function addCatListToView(listElements, catNames) {
        for(i = 0; i<catsArrayLength; i++) {
            getElementById('allCats').append(listElements[i]);
        }
    }

Upvotes: 0

Views: 358

Answers (2)

christofr
christofr

Reputation: 2700

You can use Map and forEach to clean up the code a little. Also, be careful, you were resetting var listElements = []; on each iteration.

function createArrayOfNames(catsArray) {
    return catsArray.map(function (c) {
        return c.name
    });
}

function createArrayOfListElements(catNames) {

    var listElements = [];

    catNames.forEach(function(name) {
        var listElement = new listElement();
        listElement.innerHTML = name;
        listElements.append(listElement);
    });

    return listElements;
}

function addCatListToView(listElements) {

    var catElements = getElementById('allCats');

    listElements.forEach(function(element) {
        catElements.append(element);
    };
}

Upvotes: 0

lleaff
lleaff

Reputation: 4319

Yes, creating an iterating function would be a nice way to make your code more readable.

function iterateCats(callback) {
    for(i = 0; i<catsArrayLength; i++) {
        callback(i);
    }
}

But as @squint mentioned, if you don't mind making your catsArray available to all your functions, using forEach is the standard and quicker way to achieve this.

Upvotes: 2

Related Questions