Guest User

Untitled

a guest
Sep 22nd, 2018
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. function Queue (N) {
  2. this.queue = [];
  3. this.size = N;
  4. }
  5.  
  6. /**
  7. * @description enqueues an element in the current queue.
  8. * @param {any} data to be inserted in the queue.
  9. */
  10. Queue.prototype.enqueue = function (data) {
  11. if (!this.isFull ()) {
  12. this.queue.push (data);
  13. } else {
  14. console.error ("Queue is full.");
  15. }
  16. }
  17.  
  18. /**
  19. * @description removes an element, by default, the first in the queue.
  20. */
  21. Queue.prototype.dequeue = function () {
  22. console.log ("is Empty: ", this.isEmpty ());
  23. if (!this.isEmpty ()) {
  24. return this.queue.shift ();
  25. } else {
  26. return "Queue is empty.";
  27. }
  28. }
  29.  
  30. /**
  31. * @description gets the first element, without removing it.
  32. */
  33. Queue.prototype.peek = function () {
  34. if (!this.isEmpty ()) {
  35. return this.queue[0];
  36. } else {
  37. return "Queue is empty";
  38. }
  39. }
  40.  
  41. /**
  42. * @description checks if the queue is empty.
  43. */
  44. Queue.prototype.isEmpty = function () {
  45. return !this.queue.length;
  46. }
  47.  
  48. /**
  49. * @description checks if the queue is full.
  50. */
  51. Queue.prototype.isFull = function () {
  52. return this.queue.length === this.size;
  53. }
  54.  
  55. var q = new Queue (5);
  56. console.log (q.isEmpty ());
  57. q.dequeue ();
  58. console.log (q.isFull ());
  59. q.enqueue (10);
  60. console.log (q.isEmpty ());
  61. console.log (q.isFull ());
  62. console.log (q.peek());
  63. q.enqueue (20);
  64. q.enqueue (30);
  65. q.enqueue (40);
  66. q.enqueue (50);
  67. q.enqueue (60);
  68. console.log (q.peek());
  69. console.log (q.dequeue());
  70. console.log (q.dequeue());
  71. console.log (q.dequeue());
  72. console.log (q.dequeue());
  73. console.log (q.dequeue());
  74. console.log (q.dequeue());
  75. console.log (q.peek ());
Add Comment
Please, Sign In to add comment