datastructures/stack.js

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