Skip to content

Instantly share code, notes, and snippets.

@fbacall
Created August 6, 2019 14:36
Show Gist options
  • Save fbacall/78d65a88af4ba1e659d645e11fc251a1 to your computer and use it in GitHub Desktop.
Save fbacall/78d65a88af4ba1e659d645e11fc251a1 to your computer and use it in GitHub Desktop.
Circular Queue
class CircularQueue {
constructor (size) {
this._max = size;
this._start = 0;
this._end = 0;
this._length = 0;
this._queue = new Array(size);
}
enq (item) {
this._queue[this._end] = item;
this._end = (this._end + 1) % this._max;
if (this._length === this._max) {
this._start = this._end;
} else {
this._length++;
}
}
deq () {
if (this._length) {
const item = this._queue[this._start];
this._start = (this._start + 1) % this._max;
this._length--;
return item;
}
}
each (lambda) {
for (let i = 0; i < this._length; i++) {
const result = lambda(this._queue[(this._start + i) % this._max]);
if (typeof result != 'undefined' && !result) // Stop iterating if "false" is returned
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment