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