queue.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Queue class adapted from Tim Caswell's pattern library
  2. // http://github.com/creationix/pattern/blob/master/lib/pattern/queue.js
  3. function Queue() {
  4. this.tail = [];
  5. this.head = [];
  6. this.offset = 0;
  7. }
  8. Queue.prototype.shift = function () {
  9. if (this.offset === this.head.length) {
  10. var tmp = this.head;
  11. tmp.length = 0;
  12. this.head = this.tail;
  13. this.tail = tmp;
  14. this.offset = 0;
  15. if (this.head.length === 0) {
  16. return;
  17. }
  18. }
  19. return this.head[this.offset++]; // sorry, JSLint
  20. };
  21. Queue.prototype.push = function (item) {
  22. return this.tail.push(item);
  23. };
  24. Queue.prototype.forEach = function (fn, thisv) {
  25. var array = this.head.slice(this.offset), i, il;
  26. array.push.apply(array, this.tail);
  27. if (thisv) {
  28. for (i = 0, il = array.length; i < il; i += 1) {
  29. fn.call(thisv, array[i], i, array);
  30. }
  31. } else {
  32. for (i = 0, il = array.length; i < il; i += 1) {
  33. fn(array[i], i, array);
  34. }
  35. }
  36. return array;
  37. };
  38. Queue.prototype.getLength = function () {
  39. return this.head.length - this.offset + this.tail.length;
  40. };
  41. Object.defineProperty(Queue.prototype, "length", {
  42. get: function () {
  43. return this.getLength();
  44. }
  45. });
  46. if (typeof module !== "undefined" && module.exports) {
  47. module.exports = Queue;
  48. }