Queue.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. class Queue
  2. {
  3. // initializes the queue
  4. constructor()
  5. {
  6. this.queue = [];
  7. this.offset = 0;
  8. }
  9. // Returns the length of the queue.
  10. getLength()
  11. {
  12. return (this.queue.length - this.offset);
  13. }
  14. // Returns true if the queue is empty, and false otherwise.
  15. isEmpty()
  16. {
  17. return (this.queue.length == 0);
  18. }
  19. // Enqueues x in the queue (to the end)
  20. enqueue(x)
  21. {
  22. this.queue.push(x);
  23. }
  24. // Dequeues an item and returns it. If the queue is empty, throws an error
  25. dequeue()
  26. {
  27. // if the queue is empty, throw
  28. if (this.queue.length == 0)
  29. {
  30. throw "Queue already empty!";
  31. }
  32. // store the item at the front of the queue
  33. var item = this.queue[this.offset];
  34. // increment the offset and refactor if necessary
  35. if (++ this.offset * 2 >= this.queue.length)
  36. {
  37. this.queue = this.queue.slice(this.offset);
  38. this.offset = 0;
  39. }
  40. // return the dequeued item
  41. return item;
  42. }
  43. // Returns the item at the front of the queue (without dequeuing it). If the
  44. // queue is empty then undefined is returned.
  45. peek()
  46. {
  47. return (this.queue.length > 0 ? this.queue[this.offset] : undefined);
  48. }
  49. // Deletes all the data, resets to as on construction
  50. reset()
  51. {
  52. this.queue = [];
  53. this.offset = 0;
  54. }
  55. }
  56. module.exports = Queue;