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