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