Reputation: 748
I am trying to update positions in a queue, then add to the top of the queue. If I call two updates back to back, the loop running through the queue array is not reflecting the newly added item.
The queue is an array of objects with position properties:
[
{
position: 0,
el: 'stuff'
},
{
position: 1,
el: 'stuff'
},
]
The queue is a property in a class. Here are my two methods I'm using. One for incrementing the queue and then one for adding to it.
addToQueue(el){
this.incrementQueue().push({position:0, el:el});
console.log(this.queue)
}
incrementQueue(){
for(var i = 0; i < this.queue.length; i++){
this.queue[i].position++;
if(this.queue[i].position >= this.getMax()){
this.queue.splice(i,1);
}
}
return this.queue;
}
The entire class is here:
// Code goes here
class PassActive{
constructor(options){
this.options = options || (function(){console.warn('You need to pass in an options object'); return {};})();
this.passers = this.options.passers || console.warn('You have not specified any elements to pass active between');
this.max = this.options.max || 1;
this.min = this.options.min || 0;
this.removable = this.options.removable? true : false;
this.queue = this.createQueue();
}
getMin(){
return this.min;
}
getMax(){
return this.max;
}
createQueue(){
var obj = [];
for (var i = 0; i < this.getMax(); i++) {
obj[i] = {
position: i,
el: null
};
}
return obj;
}
isQueueFull(){
var total = 0;
this.queue.forEach(function(cv, ci, arr){
if(cv.el){
total++;
}
});
if(total >= this.max){
return true;
} else {
return false;
}
}
addToQueue(el){
this.incrementQueue().push({position:0, el:el});
console.log(this.queue)
}
incrementQueue(){
for(var i = 0; i < this.queue.length; i++){
this.queue[i].position++;
if(this.queue[i].position >= this.getMax()){
this.queue.splice(i,1);
}
}
return this.queue;
}
setActive(el){
if(el.classList.contains('active')){
if(this.removable) {
el.classList.remove('active');
} else {
return;
}
} else {
el.classList.add('active');
}
}
}
var ops = {
passers: [
document.getElementById('0'),
document.getElementById('1'),
document.getElementById('2'),
document.getElementById('3'),
document.getElementById('4'),
document.getElementById('5')
],
max: 3,
min: 1,
removable: false
};
var t = new PassActive(ops);
console.log(t);
t.addToQueue('Tom');
t.addToQueue('Maureen');
There is a plnkr here
Is the array.push method asynchronous? I may be missing something simple here.
Thanks
Upvotes: 0
Views: 129
Reputation: 3878
The Problem is the splice
call in the loop. lets say on item with index 4, you splice that, this means your old item @ 5 is now @ index 4. but your loop counter jumps to 5 after 4, so you won't check the item at now index 4 (previously 5). you could do i--
in your if statement
Upvotes: 3