Upgrade to ExtJS 3.0.0 - Released 07/06/2009
[extjs.git] / src / util / MixedCollection.js
1 /*!
2  * Ext JS Library 3.0.0
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**\r
8  * @class Ext.util.MixedCollection\r
9  * @extends Ext.util.Observable\r
10  * A Collection class that maintains both numeric indexes and keys and exposes events.\r
11  * @constructor\r
12  * @param {Boolean} allowFunctions True if the addAll function should add function references to the\r
13  * collection (defaults to false)\r
14  * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection\r
15  * and return the key value for that item.  This is used when available to look up the key on items that\r
16  * were passed without an explicit key parameter to a MixedCollection method.  Passing this parameter is\r
17  * equivalent to providing an implementation for the {@link #getKey} method.\r
18  */\r
19 Ext.util.MixedCollection = function(allowFunctions, keyFn){\r
20     this.items = [];\r
21     this.map = {};\r
22     this.keys = [];\r
23     this.length = 0;\r
24     this.addEvents(\r
25         /**\r
26          * @event clear\r
27          * Fires when the collection is cleared.\r
28          */\r
29         "clear",\r
30         /**\r
31          * @event add\r
32          * Fires when an item is added to the collection.\r
33          * @param {Number} index The index at which the item was added.\r
34          * @param {Object} o The item added.\r
35          * @param {String} key The key associated with the added item.\r
36          */\r
37         "add",\r
38         /**\r
39          * @event replace\r
40          * Fires when an item is replaced in the collection.\r
41          * @param {String} key he key associated with the new added.\r
42          * @param {Object} old The item being replaced.\r
43          * @param {Object} new The new item.\r
44          */\r
45         "replace",\r
46         /**\r
47          * @event remove\r
48          * Fires when an item is removed from the collection.\r
49          * @param {Object} o The item being removed.\r
50          * @param {String} key (optional) The key associated with the removed item.\r
51          */\r
52         "remove",\r
53         "sort"\r
54     );\r
55     this.allowFunctions = allowFunctions === true;\r
56     if(keyFn){\r
57         this.getKey = keyFn;\r
58     }\r
59     Ext.util.MixedCollection.superclass.constructor.call(this);\r
60 };\r
61 \r
62 Ext.extend(Ext.util.MixedCollection, Ext.util.Observable, {\r
63     allowFunctions : false,\r
64 \r
65 /**\r
66  * Adds an item to the collection. Fires the {@link #add} event when complete.\r
67  * @param {String} key <p>The key to associate with the item, or the new item.</p>\r
68  * <p>If you supplied a {@link #getKey} implementation for this MixedCollection, or if the key\r
69  * of your stored items is in a property called <tt><b>id</b></tt>, then the MixedCollection\r
70  * will be able to <i>derive</i> the key for the new item. In this case just pass the new item in\r
71  * this parameter.</p>\r
72  * @param {Object} o The item to add.\r
73  * @return {Object} The item added.\r
74  */\r
75     add: function(key, o){\r
76         if(arguments.length == 1){\r
77             o = arguments[0];\r
78             key = this.getKey(o);\r
79         }\r
80         if(typeof key != 'undefined' && key !== null){\r
81             var old = this.map[key];\r
82             if(typeof old != 'undefined'){\r
83                 return this.replace(key, o);\r
84             }\r
85             this.map[key] = o;\r
86         }\r
87         this.length++;\r
88         this.items.push(o);\r
89         this.keys.push(key);\r
90         this.fireEvent('add', this.length-1, o, key);\r
91         return o;\r
92     },\r
93 \r
94 /**\r
95   * MixedCollection has a generic way to fetch keys if you implement getKey.  The default implementation\r
96   * simply returns <tt style="font-weight:bold;">item.id</tt> but you can provide your own implementation\r
97   * to return a different value as in the following examples:\r
98 <pre><code>\r
99 // normal way\r
100 var mc = new Ext.util.MixedCollection();\r
101 mc.add(someEl.dom.id, someEl);\r
102 mc.add(otherEl.dom.id, otherEl);\r
103 //and so on\r
104 \r
105 // using getKey\r
106 var mc = new Ext.util.MixedCollection();\r
107 mc.getKey = function(el){\r
108    return el.dom.id;\r
109 };\r
110 mc.add(someEl);\r
111 mc.add(otherEl);\r
112 \r
113 // or via the constructor\r
114 var mc = new Ext.util.MixedCollection(false, function(el){\r
115    return el.dom.id;\r
116 });\r
117 mc.add(someEl);\r
118 mc.add(otherEl);\r
119 </code></pre>\r
120  * @param {Object} item The item for which to find the key.\r
121  * @return {Object} The key for the passed item.\r
122  */\r
123     getKey : function(o){\r
124          return o.id;\r
125     },\r
126 \r
127 /**\r
128  * Replaces an item in the collection. Fires the {@link #replace} event when complete.\r
129  * @param {String} key <p>The key associated with the item to replace, or the replacement item.</p>\r
130  * <p>If you supplied a {@link #getKey} implementation for this MixedCollection, or if the key\r
131  * of your stored items is in a property called <tt><b>id</b></tt>, then the MixedCollection\r
132  * will be able to <i>derive</i> the key of the replacement item. If you want to replace an item\r
133  * with one having the same key value, then just pass the replacement item in this parameter.</p>\r
134  * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate\r
135  * with that key.\r
136  * @return {Object}  The new item.\r
137  */\r
138     replace : function(key, o){\r
139         if(arguments.length == 1){\r
140             o = arguments[0];\r
141             key = this.getKey(o);\r
142         }\r
143         var old = this.map[key];\r
144         if(typeof key == "undefined" || key === null || typeof old == "undefined"){\r
145              return this.add(key, o);\r
146         }\r
147         var index = this.indexOfKey(key);\r
148         this.items[index] = o;\r
149         this.map[key] = o;\r
150         this.fireEvent("replace", key, old, o);\r
151         return o;\r
152     },\r
153 \r
154 /**\r
155  * Adds all elements of an Array or an Object to the collection.\r
156  * @param {Object/Array} objs An Object containing properties which will be added to the collection, or\r
157  * an Array of values, each of which are added to the collection.\r
158  */\r
159     addAll : function(objs){\r
160         if(arguments.length > 1 || Ext.isArray(objs)){\r
161             var args = arguments.length > 1 ? arguments : objs;\r
162             for(var i = 0, len = args.length; i < len; i++){\r
163                 this.add(args[i]);\r
164             }\r
165         }else{\r
166             for(var key in objs){\r
167                 if(this.allowFunctions || typeof objs[key] != "function"){\r
168                     this.add(key, objs[key]);\r
169                 }\r
170             }\r
171         }\r
172     },\r
173 \r
174 /**\r
175  * Executes the specified function once for every item in the collection, passing the following arguments:\r
176  * <div class="mdetail-params"><ul>\r
177  * <li><b>item</b> : Mixed<p class="sub-desc">The collection item</p></li>\r
178  * <li><b>index</b> : Number<p class="sub-desc">The item's index</p></li>\r
179  * <li><b>length</b> : Number<p class="sub-desc">The total number of items in the collection</p></li>\r
180  * </ul></div>\r
181  * The function should return a boolean value. Returning false from the function will stop the iteration.\r
182  * @param {Function} fn The function to execute for each item.\r
183  * @param {Object} scope (optional) The scope in which to execute the function.\r
184  */\r
185     each : function(fn, scope){\r
186         var items = [].concat(this.items); // each safe for removal\r
187         for(var i = 0, len = items.length; i < len; i++){\r
188             if(fn.call(scope || items[i], items[i], i, len) === false){\r
189                 break;\r
190             }\r
191         }\r
192     },\r
193 \r
194 /**\r
195  * Executes the specified function once for every key in the collection, passing each\r
196  * key, and its associated item as the first two parameters.\r
197  * @param {Function} fn The function to execute for each item.\r
198  * @param {Object} scope (optional) The scope in which to execute the function.\r
199  */\r
200     eachKey : function(fn, scope){\r
201         for(var i = 0, len = this.keys.length; i < len; i++){\r
202             fn.call(scope || window, this.keys[i], this.items[i], i, len);\r
203         }\r
204     },\r
205 \r
206     /**\r
207      * Returns the first item in the collection which elicits a true return value from the\r
208      * passed selection function.\r
209      * @param {Function} fn The selection function to execute for each item.\r
210      * @param {Object} scope (optional) The scope in which to execute the function.\r
211      * @return {Object} The first item in the collection which returned true from the selection function.\r
212      */\r
213     find : function(fn, scope){\r
214         for(var i = 0, len = this.items.length; i < len; i++){\r
215             if(fn.call(scope || window, this.items[i], this.keys[i])){\r
216                 return this.items[i];\r
217             }\r
218         }\r
219         return null;\r
220     },\r
221 \r
222 /**\r
223  * Inserts an item at the specified index in the collection. Fires the {@link #add} event when complete.\r
224  * @param {Number} index The index to insert the item at.\r
225  * @param {String} key The key to associate with the new item, or the item itself.\r
226  * @param {Object} o (optional) If the second parameter was a key, the new item.\r
227  * @return {Object} The item inserted.\r
228  */\r
229     insert : function(index, key, o){\r
230         if(arguments.length == 2){\r
231             o = arguments[1];\r
232             key = this.getKey(o);\r
233         }\r
234         if(this.containsKey(key)){\r
235             this.suspendEvents();\r
236             this.removeKey(key);\r
237             this.resumeEvents();\r
238         }\r
239         if(index >= this.length){\r
240             return this.add(key, o);\r
241         }\r
242         this.length++;\r
243         this.items.splice(index, 0, o);\r
244         if(typeof key != "undefined" && key !== null){\r
245             this.map[key] = o;\r
246         }\r
247         this.keys.splice(index, 0, key);\r
248         this.fireEvent("add", index, o, key);\r
249         return o;\r
250     },\r
251 \r
252 /**\r
253  * Remove an item from the collection.\r
254  * @param {Object} o The item to remove.\r
255  * @return {Object} The item removed or false if no item was removed.\r
256  */\r
257     remove : function(o){\r
258         return this.removeAt(this.indexOf(o));\r
259     },\r
260 \r
261 /**\r
262  * Remove an item from a specified index in the collection. Fires the {@link #remove} event when complete.\r
263  * @param {Number} index The index within the collection of the item to remove.\r
264  * @return {Object} The item removed or false if no item was removed.\r
265  */\r
266     removeAt : function(index){\r
267         if(index < this.length && index >= 0){\r
268             this.length--;\r
269             var o = this.items[index];\r
270             this.items.splice(index, 1);\r
271             var key = this.keys[index];\r
272             if(typeof key != "undefined"){\r
273                 delete this.map[key];\r
274             }\r
275             this.keys.splice(index, 1);\r
276             this.fireEvent("remove", o, key);\r
277             return o;\r
278         }\r
279         return false;\r
280     },\r
281 \r
282 /**\r
283  * Removed an item associated with the passed key fom the collection.\r
284  * @param {String} key The key of the item to remove.\r
285  * @return {Object} The item removed or false if no item was removed.\r
286  */\r
287     removeKey : function(key){\r
288         return this.removeAt(this.indexOfKey(key));\r
289     },\r
290 \r
291 /**\r
292  * Returns the number of items in the collection.\r
293  * @return {Number} the number of items in the collection.\r
294  */\r
295     getCount : function(){\r
296         return this.length;\r
297     },\r
298 \r
299 /**\r
300  * Returns index within the collection of the passed Object.\r
301  * @param {Object} o The item to find the index of.\r
302  * @return {Number} index of the item. Returns -1 if not found.\r
303  */\r
304     indexOf : function(o){\r
305         return this.items.indexOf(o);\r
306     },\r
307 \r
308 /**\r
309  * Returns index within the collection of the passed key.\r
310  * @param {String} key The key to find the index of.\r
311  * @return {Number} index of the key.\r
312  */\r
313     indexOfKey : function(key){\r
314         return this.keys.indexOf(key);\r
315     },\r
316 \r
317 /**\r
318  * Returns the item associated with the passed key OR index. Key has priority over index.  This is the equivalent\r
319  * of calling {@link #key} first, then if nothing matched calling {@link #itemAt}.\r
320  * @param {String/Number} key The key or index of the item.\r
321  * @return {Object} If the item is found, returns the item.  If the item was not found, returns <tt>undefined</tt>.\r
322  * If an item was found, but is a Class, returns <tt>null</tt>.\r
323  */\r
324     item : function(key){\r
325         var mk = this.map[key],\r
326             item = mk !== undefined ? mk : (typeof key == 'number') ? this.items[key] : undefined;\r
327         return !Ext.isFunction(item) || this.allowFunctions ? item : null; // for prototype!\r
328     },\r
329 \r
330 /**\r
331  * Returns the item at the specified index.\r
332  * @param {Number} index The index of the item.\r
333  * @return {Object} The item at the specified index.\r
334  */\r
335     itemAt : function(index){\r
336         return this.items[index];\r
337     },\r
338 \r
339 /**\r
340  * Returns the item associated with the passed key.\r
341  * @param {String/Number} key The key of the item.\r
342  * @return {Object} The item associated with the passed key.\r
343  */\r
344     key : function(key){\r
345         return this.map[key];\r
346     },\r
347 \r
348 /**\r
349  * Returns true if the collection contains the passed Object as an item.\r
350  * @param {Object} o  The Object to look for in the collection.\r
351  * @return {Boolean} True if the collection contains the Object as an item.\r
352  */\r
353     contains : function(o){\r
354         return this.indexOf(o) != -1;\r
355     },\r
356 \r
357 /**\r
358  * Returns true if the collection contains the passed Object as a key.\r
359  * @param {String} key The key to look for in the collection.\r
360  * @return {Boolean} True if the collection contains the Object as a key.\r
361  */\r
362     containsKey : function(key){\r
363         return typeof this.map[key] != "undefined";\r
364     },\r
365 \r
366 /**\r
367  * Removes all items from the collection.  Fires the {@link #clear} event when complete.\r
368  */\r
369     clear : function(){\r
370         this.length = 0;\r
371         this.items = [];\r
372         this.keys = [];\r
373         this.map = {};\r
374         this.fireEvent("clear");\r
375     },\r
376 \r
377 /**\r
378  * Returns the first item in the collection.\r
379  * @return {Object} the first item in the collection..\r
380  */\r
381     first : function(){\r
382         return this.items[0];\r
383     },\r
384 \r
385 /**\r
386  * Returns the last item in the collection.\r
387  * @return {Object} the last item in the collection..\r
388  */\r
389     last : function(){\r
390         return this.items[this.length-1];\r
391     },\r
392 \r
393     // private\r
394     _sort : function(property, dir, fn){\r
395         var i,\r
396             len,\r
397             dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1,\r
398             c = [], k = this.keys, items = this.items;\r
399             \r
400         fn = fn || function(a, b){\r
401             return a-b;\r
402         };\r
403         for(i = 0, len = items.length; i < len; i++){\r
404             c[c.length] = {key: k[i], value: items[i], index: i};\r
405         }\r
406         c.sort(function(a, b){\r
407             var v = fn(a[property], b[property]) * dsc;\r
408             if(v === 0){\r
409                 v = (a.index < b.index ? -1 : 1);\r
410             }\r
411             return v;\r
412         });\r
413         for(i = 0, len = c.length; i < len; i++){\r
414             items[i] = c[i].value;\r
415             k[i] = c[i].key;\r
416         }\r
417         this.fireEvent("sort", this);\r
418     },\r
419 \r
420     /**\r
421      * Sorts this collection with the passed comparison function\r
422      * @param {String} direction (optional) "ASC" or "DESC"\r
423      * @param {Function} fn (optional) comparison function\r
424      */\r
425     sort : function(dir, fn){\r
426         this._sort("value", dir, fn);\r
427     },\r
428 \r
429     /**\r
430      * Sorts this collection by keys\r
431      * @param {String} direction (optional) "ASC" or "DESC"\r
432      * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)\r
433      */\r
434     keySort : function(dir, fn){\r
435         this._sort("key", dir, fn || function(a, b){\r
436             var v1 = String(a).toUpperCase(), v2 = String(b).toUpperCase();\r
437             return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);\r
438         });\r
439     },\r
440 \r
441     /**\r
442      * Returns a range of items in this collection\r
443      * @param {Number} startIndex (optional) defaults to 0\r
444      * @param {Number} endIndex (optional) default to the last item\r
445      * @return {Array} An array of items\r
446      */\r
447     getRange : function(start, end){\r
448         var items = this.items;\r
449         if(items.length < 1){\r
450             return [];\r
451         }\r
452         start = start || 0;\r
453         end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);\r
454         var i, r = [];\r
455         if(start <= end){\r
456             for(i = start; i <= end; i++) {\r
457                 r[r.length] = items[i];\r
458             }\r
459         }else{\r
460             for(i = start; i >= end; i--) {\r
461                 r[r.length] = items[i];\r
462             }\r
463         }\r
464         return r;\r
465     },\r
466 \r
467     /**\r
468      * Filter the <i>objects</i> in this collection by a specific property.\r
469      * Returns a new collection that has been filtered.\r
470      * @param {String} property A property on your objects\r
471      * @param {String/RegExp} value Either string that the property values\r
472      * should start with or a RegExp to test against the property\r
473      * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning\r
474      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison (defaults to False).\r
475      * @return {MixedCollection} The new filtered collection\r
476      */\r
477     filter : function(property, value, anyMatch, caseSensitive){\r
478         if(Ext.isEmpty(value, false)){\r
479             return this.clone();\r
480         }\r
481         value = this.createValueMatcher(value, anyMatch, caseSensitive);\r
482         return this.filterBy(function(o){\r
483             return o && value.test(o[property]);\r
484         });\r
485     },\r
486 \r
487     /**\r
488      * Filter by a function. Returns a <i>new</i> collection that has been filtered.\r
489      * The passed function will be called with each object in the collection.\r
490      * If the function returns true, the value is included otherwise it is filtered.\r
491      * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)\r
492      * @param {Object} scope (optional) The scope of the function (defaults to this)\r
493      * @return {MixedCollection} The new filtered collection\r
494      */\r
495     filterBy : function(fn, scope){\r
496         var r = new Ext.util.MixedCollection();\r
497         r.getKey = this.getKey;\r
498         var k = this.keys, it = this.items;\r
499         for(var i = 0, len = it.length; i < len; i++){\r
500             if(fn.call(scope||this, it[i], k[i])){\r
501                 r.add(k[i], it[i]);\r
502             }\r
503         }\r
504         return r;\r
505     },\r
506 \r
507     /**\r
508      * Finds the index of the first matching object in this collection by a specific property/value.\r
509      * @param {String} property The name of a property on your objects.\r
510      * @param {String/RegExp} value A string that the property values\r
511      * should start with or a RegExp to test against the property.\r
512      * @param {Number} start (optional) The index to start searching at (defaults to 0).\r
513      * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning.\r
514      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison.\r
515      * @return {Number} The matched index or -1\r
516      */\r
517     findIndex : function(property, value, start, anyMatch, caseSensitive){\r
518         if(Ext.isEmpty(value, false)){\r
519             return -1;\r
520         }\r
521         value = this.createValueMatcher(value, anyMatch, caseSensitive);\r
522         return this.findIndexBy(function(o){\r
523             return o && value.test(o[property]);\r
524         }, null, start);\r
525     },\r
526 \r
527     /**\r
528      * Find the index of the first matching object in this collection by a function.\r
529      * If the function returns <i>true</i> it is considered a match.\r
530      * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key).\r
531      * @param {Object} scope (optional) The scope of the function (defaults to this).\r
532      * @param {Number} start (optional) The index to start searching at (defaults to 0).\r
533      * @return {Number} The matched index or -1\r
534      */\r
535     findIndexBy : function(fn, scope, start){\r
536         var k = this.keys, it = this.items;\r
537         for(var i = (start||0), len = it.length; i < len; i++){\r
538             if(fn.call(scope||this, it[i], k[i])){\r
539                 return i;\r
540             }\r
541         }\r
542         return -1;\r
543     },\r
544 \r
545     // private\r
546     createValueMatcher : function(value, anyMatch, caseSensitive){\r
547         if(!value.exec){ // not a regex\r
548             value = String(value);\r
549             value = new RegExp((anyMatch === true ? '' : '^') + Ext.escapeRe(value), caseSensitive ? '' : 'i');\r
550         }\r
551         return value;\r
552     },\r
553 \r
554     /**\r
555      * Creates a shallow copy of this collection\r
556      * @return {MixedCollection}\r
557      */\r
558     clone : function(){\r
559         var r = new Ext.util.MixedCollection();\r
560         var k = this.keys, it = this.items;\r
561         for(var i = 0, len = it.length; i < len; i++){\r
562             r.add(k[i], it[i]);\r
563         }\r
564         r.getKey = this.getKey;\r
565         return r;\r
566     }\r
567 });\r
568 /**\r
569  * This method calls {@link #item item()}.\r
570  * Returns the item associated with the passed key OR index. Key has priority over index.  This is the equivalent\r
571  * of calling {@link #key} first, then if nothing matched calling {@link #itemAt}.\r
572  * @param {String/Number} key The key or index of the item.\r
573  * @return {Object} If the item is found, returns the item.  If the item was not found, returns <tt>undefined</tt>.\r
574  * If an item was found, but is a Class, returns <tt>null</tt>.\r
575  */\r
576 Ext.util.MixedCollection.prototype.get = Ext.util.MixedCollection.prototype.item;