Created
August 6, 2019 14:36
-
-
Save fbacall/78d65a88af4ba1e659d645e11fc251a1 to your computer and use it in GitHub Desktop.
Circular Queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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