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