reactive-list.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. // #ReactiveList
  2. // Provides a simple reactive list interface
  3. var _noopCallback = function() {};
  4. var _nonReactive = {
  5. changed: _noopCallback,
  6. depend: _noopCallback
  7. };
  8. /** @method ReactiveList Keeps a reactive list of key+value items
  9. * @constructor
  10. * @namespace ReactiveList
  11. * @param {object} [options]
  12. * @param {function} sort The sort algorithm to use
  13. * @param {boolean} [reactive=true] If set false this list is not reactive
  14. * Example:
  15. * ```js
  16. * var list = new ReactiveList();
  17. * list.insert(1, { text: 'Hello id: 1' });
  18. * list.insert(2, { text: 'Hello id: 2' });
  19. * list.insert(3, { text: 'Hello id: 3' });
  20. * list.update(2, { text: 'Updated 2'});
  21. * list.remove(1);
  22. *
  23. * list.forEach(function(value, key) {
  24. * console.log('GOT: ' + value.text);
  25. * }, true); // Set noneReactive = true, default behaviour is reactive
  26. *
  27. * // Return from Template:
  28. * Template.hello.list = function() {
  29. * return list.fetch();
  30. * };
  31. * ```
  32. *
  33. * ####Example of a sort algorithm
  34. * Sort can be used to define the order of the list
  35. * ```js
  36. * var list = new ReactiveList({
  37. * sort: function(a, b) {
  38. * // a and b are type of { key, value }
  39. * // here we sort by the key:
  40. * return a.key < b.key;
  41. * }
  42. * });
  43. * ```
  44. * ###Object chain
  45. * ```
  46. * first last
  47. * undefined - obj - obj - obj - undefined
  48. * (prev value next) (prev value next) (prev value next)
  49. * ```
  50. */
  51. ReactiveList = function(options) {
  52. var self = this;
  53. // Object container
  54. self.lookup = {};
  55. // Length
  56. self._length = 0;
  57. // First object in list
  58. self.first;
  59. // Last object in list
  60. self.last;
  61. // Set sort to options.sort or default to true (asc)
  62. self.sort = (options && options.sort || function(a, b) {
  63. return a.key < b.key;
  64. });
  65. // Allow user to disable reactivity, default true
  66. self.isReactive = (options)? options.reactive !== false : true;
  67. // If lifo queue
  68. if (options === true || options && options.sort === true) {
  69. self.sort = function(a, b) { return a.key > b.key; };
  70. }
  71. // Rig the dependencies
  72. self._listDeps = (self.isReactive)? new Deps.Dependency() : _nonReactive;
  73. self._lengthDeps = (self.isReactive)? new Deps.Dependency() : _nonReactive;
  74. };
  75. /** @method ReactiveList.prototype.length Returns the length of the list
  76. * @reactive
  77. * @returns {number} Length of the reactive list
  78. */
  79. ReactiveList.prototype.length = function() {
  80. var self = this;
  81. // Make this reactive
  82. self._lengthDeps.depend();
  83. return self._length;
  84. };
  85. /** @method ReactiveList.prototype.reset Reset and empty the list
  86. * @todo Check for memory leaks, if so we have to iterate over lookup and delete the items
  87. */
  88. ReactiveList.prototype.reset = function() {
  89. var self = this;
  90. // Clear the reference to the first object
  91. self.first = undefined;
  92. // Clear the reference to the last object
  93. self.last = undefined;
  94. // Clear the lookup object
  95. self.lookup = {};
  96. // Set the length to 0
  97. self._length = 0;
  98. self._lengthDeps.changed();
  99. // Invalidate the list
  100. self._listDeps.changed();
  101. };
  102. /** @method ReactiveList.prototype.update
  103. * @param {string|number} key Key to update
  104. * @param {any} value Update with this value
  105. */
  106. ReactiveList.prototype.update = function(key, value) {
  107. var self = this;
  108. // Make sure the key is found in the list
  109. if (typeof self.lookup[key] === 'undefined') {
  110. throw new Error('Reactive list cannot update, key "' + key + '" not found');
  111. }
  112. // Set the new value
  113. self.lookup[key].value = value;
  114. // Invalidate the list
  115. self._listDeps.changed();
  116. };
  117. /** @method ReactiveList.prototype.insert
  118. * @param {string|number} key Key to insert
  119. * @param {any} value Insert item with this value
  120. */
  121. ReactiveList.prototype.insert = function(key, value) {
  122. var self = this;
  123. if (typeof self.lookup[key] !== 'undefined') {
  124. throw new Error('Reactive list could not insert: key "' + key +
  125. '" allready found');
  126. }
  127. // Create the new item to insert into the list
  128. var newItem = { key: key, value: value };
  129. // Init current by pointing it at the first object in the list
  130. var current = self.first;
  131. // Init the isInserted flag
  132. var isInserted = false;
  133. // Iterate through list while not empty and item is not inserted
  134. while (typeof current !== 'undefined' && !isInserted) {
  135. // Sort the list by using the sort function
  136. if (self.sort(newItem, current)) {
  137. // Insert self.lookup[key] before
  138. if (typeof current.prev === 'undefined') { self.first = newItem; }
  139. // Set the references in the inserted object
  140. newItem.prev = current.prev;
  141. newItem.next = current;
  142. // Update the two existing objects
  143. if (current.prev) { current.prev.next = newItem; }
  144. current.prev = newItem;
  145. // Mark the item as inserted - job's done
  146. isInserted = true;
  147. }
  148. // Goto next object
  149. current = current.next;
  150. }
  151. if (!isInserted) {
  152. // We append it to the list
  153. newItem.prev = self.last;
  154. if (self.last) { self.last.next = newItem; }
  155. // Update the last pointing to newItem
  156. self.last = newItem;
  157. // Update first if we are appending to an empty list
  158. if (self._length === 0) { self.first = newItem; }
  159. }
  160. // Reference the object for a quick lookup option
  161. self.lookup[key] = newItem;
  162. // Increase length
  163. self._length++;
  164. self._lengthDeps.changed();
  165. // And invalidate the list
  166. self._listDeps.changed();
  167. };
  168. /** @method ReactiveList.prototype.remove
  169. * @param {string|number} key Key to remove
  170. */
  171. ReactiveList.prototype.remove = function(key) {
  172. var self = this;
  173. // Get the item object
  174. var item = self.lookup[key];
  175. // Check that it exists
  176. if (typeof item === 'undefined') {
  177. return;
  178. // throw new Error('ReactiveList cannot remove item, unknow key "' + key +
  179. // '"');
  180. }
  181. // Rig the references
  182. var prevItem = item.prev;
  183. var nextItem = item.next;
  184. // Update chain prev object next reference
  185. if (typeof prevItem !== 'undefined') {
  186. prevItem.next = nextItem;
  187. } else {
  188. self.first = nextItem;
  189. }
  190. // Update chain next object prev reference
  191. if (typeof nextItem !== 'undefined') {
  192. nextItem.prev = prevItem;
  193. } else {
  194. self.last = prevItem;
  195. }
  196. // Clean up
  197. self.lookup[key].last = null;
  198. self.lookup[key].prev = null;
  199. self.lookup[key] = null;
  200. prevItem = null;
  201. delete self.lookup[key];
  202. // Decrease the length
  203. self._length--;
  204. self._lengthDeps.changed();
  205. // Invalidate the list
  206. self._listDeps.changed();
  207. };
  208. /** @method ReactiveList.prototype.getLastItem
  209. * @returns {any} Pops last item from the list - removes the item from the list
  210. */
  211. ReactiveList.prototype.getLastItem = function(first) {
  212. var self = this;
  213. // Get the relevant item first or last
  214. var item = (first)?self.first: self.last;
  215. if (typeof item === 'undefined') {
  216. return; // Empty list
  217. }
  218. // Remove the item from the list
  219. self.remove(item.key);
  220. // Return the value
  221. return item.value;
  222. };
  223. /** @method ReactiveList.prototype.getFirstItem
  224. * @returns {any} Pops first item from the list - removes the item from the list
  225. */
  226. ReactiveList.prototype.getFirstItem = function() {
  227. // This gets the first item...
  228. return this.getLastItem(true);
  229. };
  230. /** @method ReactiveList.prototype.forEach
  231. * @param {function} f Callback `funciton(value, key)`
  232. * @param {boolean} [noneReactive=false] Set true if want to disable reactivity
  233. * @param {boolean} [reverse=false] Set true to reverse iteration `forEachReverse`
  234. */
  235. ReactiveList.prototype.forEach = function(f, noneReactive, reverse) {
  236. var self = this;
  237. // Check if f is a function
  238. if (typeof f !== 'function') {
  239. throw new Error('ReactiveList forEach requires a function');
  240. }
  241. // We allow this not to be reactive
  242. if (!noneReactive) { self._listDeps.depend(); }
  243. // Set current to the first object
  244. var current = (reverse)?self.last: self.first;
  245. // Iterate over the list while its not empty
  246. while (current) {
  247. // Call the callback function
  248. f(current.value, current.key);
  249. // Jump to the next item in the list
  250. current = (reverse)?current.prev: current.next;
  251. }
  252. };
  253. /** @method ReactiveList.prototype.forEachReverse
  254. * @param {function} f Callback `funciton(value, key)`
  255. * @param {boolean} [noneReactive=false] Set true if want to disable reactivity
  256. */
  257. ReactiveList.prototype.forEachReverse = function(f, noneReactive) {
  258. // Call forEach with the reverse flag
  259. this.forEach(f, noneReactive, true);
  260. };
  261. /** @method ReactiveList.prototype.fetch Returns list as array
  262. * @param {boolean} [noneReactive=false] Set true if want to disable reactivity
  263. * @reactive This can be disabled
  264. * @returns {array} List of items
  265. */
  266. ReactiveList.prototype.fetch = function(noneReactive) {
  267. var self = this;
  268. // Init the result buffer
  269. var result = [];
  270. // Iterate over the list items
  271. self.forEach(function fetchCallback(value) {
  272. // Add the item value to the result
  273. result.push(value);
  274. }, noneReactive);
  275. // Return the result
  276. return result;
  277. };