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