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