ElggPriorityList.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /**
  2. * Priority lists allow you to create an indexed list that can be iterated through in a specific
  3. * order.
  4. */
  5. elgg.ElggPriorityList = function() {
  6. this.length = 0;
  7. this.priorities_ = [];
  8. };
  9. /**
  10. * Inserts an element into the priority list at the priority specified.
  11. *
  12. * @param {Object} obj The object to insert
  13. * @param {Number} opt_priority An optional priority to insert at.
  14. *
  15. * @return {Void}
  16. */
  17. elgg.ElggPriorityList.prototype.insert = function(obj, opt_priority) {
  18. var priority = 500;
  19. if (arguments.length == 2 && opt_priority !== undefined) {
  20. priority = parseInt(opt_priority, 10);
  21. }
  22. priority = Math.max(priority, 0);
  23. if (elgg.isUndefined(this.priorities_[priority])) {
  24. this.priorities_[priority] = [];
  25. }
  26. this.priorities_[priority].push(obj);
  27. this.length++;
  28. };
  29. /**
  30. * Iterates through each element in order.
  31. *
  32. * Unlike every, this ignores the return value of the callback.
  33. *
  34. * @param {Function} callback The callback function to pass each element through. See
  35. * Array.prototype.every() for details.
  36. * @return {Object}
  37. */
  38. elgg.ElggPriorityList.prototype.forEach = function(callback) {
  39. elgg.assertTypeOf('function', callback);
  40. var index = 0;
  41. this.priorities_.forEach(function(elems) {
  42. elems.forEach(function(elem) {
  43. callback(elem, index++);
  44. });
  45. });
  46. return this;
  47. };
  48. /**
  49. * Iterates through each element in order.
  50. *
  51. * Unlike forEach, this returns the value of the callback and will break on false.
  52. *
  53. * @param {Function} callback The callback function to pass each element through. See
  54. * Array.prototype.every() for details.
  55. * @return {Object}
  56. */
  57. elgg.ElggPriorityList.prototype.every = function(callback) {
  58. elgg.assertTypeOf('function', callback);
  59. var index = 0;
  60. return this.priorities_.every(function(elems) {
  61. return elems.every(function(elem) {
  62. return callback(elem, index++);
  63. });
  64. });
  65. };
  66. /**
  67. * Removes an element from the priority list
  68. *
  69. * @param {Object} obj The object to remove.
  70. * @return {Void}
  71. */
  72. elgg.ElggPriorityList.prototype.remove = function(obj) {
  73. this.priorities_.forEach(function(elems) {
  74. var index;
  75. while ((index = elems.indexOf(obj)) !== -1) {
  76. elems.splice(index, 1);
  77. this.length--;
  78. }
  79. });
  80. };