Created
October 20, 2015 09:30
-
-
Save rangercyh/232ab2a813ad6ba95d4b to your computer and use it in GitHub Desktop.
js queue implement
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
var Queue = function() { | |
this.tail = []; | |
this.head = []; | |
this.offset = 0; | |
}; | |
module.exports = Queue; | |
Queue.prototype.shift = function () { | |
if (this.offset === this.head.length) { | |
var tmp = this.head; | |
tmp.length = 0; | |
this.head = this.tail; | |
this.tail = tmp; | |
this.offset = 0; | |
if (this.head.length === 0) { | |
return; | |
} | |
} | |
return this.head[this.offset++]; | |
}; | |
Queue.prototype.push = function (item) { | |
return this.tail.push(item); | |
}; | |
Queue.prototype.getLength = function () { | |
return this.head.length - this.offset + this.tail.length; | |
}; | |
Queue.prototype.first = function() { | |
if (this.offset === this.head.length) { | |
return this.tail[0]; | |
} | |
return this.head[this.offset]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment