datastructures/queue.js

  1. 'use strict';
  2. /**
  3. * Create a FIFO queue data structure.
  4. * @constructor
  5. */
  6. function Queue() {
  7. this.q = [];
  8. }
  9. /**
  10. * Get the number of objects in the queue.
  11. * @returns {number} Number of elements in the queue.
  12. */
  13. Queue.prototype.size = function() {
  14. return this.q.length;
  15. };
  16. /**
  17. * Clear the contents of the queue.
  18. */
  19. Queue.prototype.clear = function() {
  20. this.q = [];
  21. };
  22. /**
  23. * Push an object in to the queue.
  24. * @param {object} obj - Any object to be pushed into the queue.
  25. */
  26. Queue.prototype.enqueue = function(obj) {
  27. this.q.push(obj);
  28. };
  29. /**
  30. * Get the front element of the queue and removes it from the queue.
  31. * @returns {object} Front element from the queue.
  32. */
  33. Queue.prototype.dequeue = function() {
  34. var obj = this.q[0];
  35. this.q.splice(0,1);
  36. return obj;
  37. };
  38. /**
  39. * Get the front element of the queue without removing it from the queue.
  40. * @returns {object} Front element from the queue.
  41. */
  42. Queue.prototype.peek = function() {
  43. var obj = this.q[0];
  44. return obj;
  45. };
  46. /**
  47. * Checks if the queue isn't empty.
  48. * @returns {boolean} Whether or not the queue has another element. True if yes.
  49. */
  50. Queue.prototype.hasNext = function() {
  51. return this.q.length !== 0;
  52. };
  53. /**
  54. * Checks if the queue is empty.
  55. * @returns {boolean} Whether or not the queue is empty. True if yes.
  56. */
  57. Queue.prototype.isEmpty = function() {
  58. return this.q.length === 0;
  59. };
  60. module.exports = Queue;