queue.js 1.4 KB

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