Queue.js 852 B

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