Queue.js.bad 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. class Queue
  2. {
  3. // initializes the queue
  4. constructor()
  5. {
  6. this.arr = [];
  7. this.pos = 0;
  8. }
  9. // uses the array x to fill the queue
  10. makeFilled(x)
  11. {
  12. this.arr = x;
  13. this.pos = 0;
  14. }
  15. // Returns true if the queue is empty, and false otherwise.
  16. isEmpty()
  17. {
  18. return (this.arr.length == 0 || this.pos == (this.arr.length - 1));
  19. }
  20. getPos()
  21. {
  22. return this.pos;
  23. }
  24. // Enqueues x in the queue (to the end)
  25. enqueue(x)
  26. {
  27. this.arr.push(x);
  28. }
  29. // enqueues x to position i
  30. insert(x, i)
  31. {
  32. this.arr.splice(i, 0, x);
  33. }
  34. // removes item at index i
  35. remove(i)
  36. {
  37. this.arr.splice(i, 1);
  38. }
  39. // Dequeues an item and returns it. If the queue is empty, throws an error
  40. dequeue()
  41. {
  42. // if the queue is empty, throw
  43. if (this.arr.length == 0)
  44. {
  45. throw "Queue empty!";
  46. }
  47. // if the queue is at the end already, return undefined
  48. if (this.pos >= this.arr.length)
  49. {
  50. return undefined;
  51. }
  52. // store the item at the front of the queue
  53. var item = this.arr[this.pos];
  54. ++this.pos;
  55. // return the dequeued item
  56. return item;
  57. }
  58. // Returns the item at the front of the queue (without dequeuing it). If the
  59. // queue is empty then undefined is returned.
  60. peek()
  61. {
  62. return (this.arr.length > 0 ? this.arr[this.pos] : undefined);
  63. }
  64. // returns an array of all items in the queue (again, without dequeuing) from the current pos.
  65. read()
  66. {
  67. return this.arr.slice(this.pos);
  68. }
  69. // Deletes all the data, resets to as on construction
  70. reset()
  71. {
  72. this.arr = [];
  73. this.pos = 0;
  74. }
  75. }
  76. module.exports = QueueButBad;