Stack.js 863 B

1234567891011121314151617181920212223242526272829303132333435
  1. var Class = require('./Class');
  2. var reverse = require('./reverse');
  3. exports = Class({
  4. initialize: function Stack() {
  5. this.clear();
  6. },
  7. clear: function() {
  8. this._items = [];
  9. this.size = 0;
  10. },
  11. push: function(item) {
  12. this._items.push(item);
  13. return ++this.size;
  14. },
  15. pop: function() {
  16. if (!this.size) return;
  17. this.size--;
  18. return this._items.pop();
  19. },
  20. peek: function() {
  21. return this._items[this.size - 1];
  22. },
  23. forEach: function(iterator, ctx) {
  24. ctx = arguments.length > 1 ? ctx : this;
  25. var items = this._items;
  26. for (var i = this.size - 1, j = 0; i >= 0; i--, j++) {
  27. iterator.call(ctx, items[i], j, this);
  28. }
  29. },
  30. toArr: function() {
  31. return reverse(this._items);
  32. }
  33. });
  34. module.exports = exports;