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