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