Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement