Queue.js 1.8 KB

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