Stack.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import EmptyStackException from './EmptyStackException'
  2. import IndexOutOfBoundsException from '../lang/IndexOutOfBoundsException'
  3. import List from './List'
  4. /**
  5. * @see http://download.oracle.com/javase/6/docs/api/java/util/Stack.html
  6. */
  7. export default class Stack extends List {
  8. constructor() {
  9. super()
  10. this.array = []
  11. }
  12. add(e) {
  13. this.array.push(e)
  14. return true
  15. }
  16. get(index) {
  17. if (index < 0 || index >= this.size())
  18. throw new IndexOutOfBoundsException()
  19. return this.array[index]
  20. }
  21. /**
  22. * Pushes an item onto the top of this stack.
  23. * @param {Object} e
  24. * @return {Object}
  25. */
  26. push(e) {
  27. this.array.push(e)
  28. return e
  29. }
  30. /**
  31. * Removes the object at the top of this stack and returns that object as the value of this function.
  32. * @return {Object}
  33. */
  34. pop() {
  35. if (this.array.length === 0)
  36. throw new EmptyStackException()
  37. return this.array.pop()
  38. }
  39. /**
  40. * Looks at the object at the top of this stack without removing it from the
  41. * stack.
  42. * @return {Object}
  43. */
  44. peek() {
  45. if (this.array.length === 0)
  46. throw new EmptyStackException()
  47. return this.array[this.array.length - 1]
  48. }
  49. /**
  50. * Tests if this stack is empty.
  51. * @return {boolean} true if and only if this stack contains no items; false
  52. * otherwise.
  53. */
  54. empty() {
  55. return this.array.length === 0
  56. }
  57. /**
  58. * @return {boolean}
  59. */
  60. isEmpty() {
  61. return this.empty()
  62. }
  63. /**
  64. * Returns the 1-based position where an object is on this stack. If the object
  65. * o occurs as an item in this stack, this method returns the distance from the
  66. * top of the stack of the occurrence nearest the top of the stack; the topmost
  67. * item on the stack is considered to be at distance 1. The equals method is
  68. * used to compare o to the items in this stack.
  69. *
  70. * NOTE: does not currently actually use equals. (=== is used)
  71. *
  72. * @param {Object} o
  73. * @return {number} the 1-based position from the top of the stack where the
  74. * object is located; the return value -1 indicates that the object is
  75. * not on the stack.
  76. */
  77. search(o) {
  78. return this.array.indexOf(o)
  79. }
  80. /**
  81. * @return {number}
  82. */
  83. size() {
  84. return this.array.length
  85. }
  86. /**
  87. * @return {Array}
  88. */
  89. toArray() {
  90. return this.array.slice()
  91. }
  92. }