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