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