dequeue.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. var Dequeue = exports = module.exports = function Dequeue() {
  2. this.head = new Node()
  3. this.length = 0
  4. }
  5. Dequeue.prototype.push = function(d){
  6. var n = new Node(d)
  7. this.head.prepend(n)
  8. this.length += 1
  9. return this
  10. }
  11. Dequeue.prototype.unshift = function(d){
  12. var n = new Node(d)
  13. this.head.append(n)
  14. this.length += 1
  15. return this
  16. }
  17. Dequeue.prototype.pop = function(){
  18. if (this.head.prev === this.head) return
  19. var n = this.head.prev.remove()
  20. this.length -= 1
  21. return n.data
  22. }
  23. Dequeue.prototype.shift = function(){
  24. if (this.head.next === this.head) return
  25. var n = this.head.next.remove()
  26. this.length -= 1
  27. return n.data
  28. }
  29. Dequeue.prototype.empty = function(){
  30. if (this.length === 0 ) return
  31. //no node points to head; not necessary for GC, but it makes me feel better.
  32. this.head.next.prev = null
  33. this.head.prev.next = null
  34. //head only points to itself; as a fresh node would
  35. this.head.next = this.head
  36. this.head.prev = this.head
  37. this.length = 0
  38. return
  39. }
  40. function Node(d) {
  41. this.data = d
  42. this.next = this
  43. this.prev = this
  44. }
  45. Node.prototype.append = function(n) {
  46. n.next = this.next
  47. n.prev = this
  48. this.next.prev = n
  49. this.next = n
  50. return n
  51. }
  52. Node.prototype.prepend = function(n) {
  53. n.prev = this.prev
  54. n.next = this
  55. this.prev.next = n
  56. this.prev = n
  57. return n
  58. }
  59. Node.prototype.remove = function() {
  60. this.next.prev = this.prev
  61. this.prev.next = this.next
  62. return this
  63. }