deb0rian
deb0rian

Reputation: 976

How to loop arrays and keep the indexing grow between them?

I'm doing it in , but it's not really based on any language. Just a logic which I seem to misunderstand.

I have a parking system with different parking spots (for cars, moto, large cars, etc).

To initialize parking system, I have to loop through the initial settings array and create empty spots with specifying each ID and type.

I did it like this:

Here's my config, the numbers and capacity types can be added before any initialization of the system

var config = {
    capacityPerType: {
        compact: 150,
        large: 100
    }
}

manager = new Manager(config);

Here's how I loop through all types and assign them a spot ID:

    var counterAdd = 0;
    for(slotType in config.capacityPerType) {

        var capacityPerType = parseInt( config.capacityPerType[slotType] );
        for(var i = 1; i <= capacityPerType; i++) {
            var newId = i + counterAdd;

            if (!this.defaults.slots[slotType]) {
                this.defaults.slots[slotType] = [];
            }
            this.defaults.slots[slotType][newId] = new Slot({id:newId,type:slotType});
        }

        counterAdd = capacityPerType;
    }

Honestly, that's a code smell. It will work ONLY with 2 types, and unless the second type is lower than the first type.

Any ideas how to keep looping and preserving the counter number? :/

Upvotes: 0

Views: 64

Answers (1)

Jamiec
Jamiec

Reputation: 136239

I think all you need is

counterAdd += capacityPerType;

in place of

counterAdd = capacityPerType;

Also, you dont need to parseInt a few lines above - its already an int!

Here's a jsfiddle to confirm the above: http://jsfiddle.net/f7stn/1/

Upvotes: 1

Related Questions