3 * Copyright(c) 2006-2010 Ext JS, Inc.
5 * http://www.extjs.com/license
8 * @class Ext.util.MixedCollection
9 * @extends Ext.util.Observable
10 * A Collection class that maintains both numeric indexes and keys and exposes events.
12 * @param {Boolean} allowFunctions Specify <tt>true</tt> if the {@link #addAll}
13 * function should add function references to the collection. Defaults to
15 * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
16 * and return the key value for that item. This is used when available to look up the key on items that
17 * were passed without an explicit key parameter to a MixedCollection method. Passing this parameter is
18 * equivalent to providing an implementation for the {@link #getKey} method.
20 Ext.util.MixedCollection = function(allowFunctions, keyFn){
28 * Fires when the collection is cleared.
33 * Fires when an item is added to the collection.
34 * @param {Number} index The index at which the item was added.
35 * @param {Object} o The item added.
36 * @param {String} key The key associated with the added item.
41 * Fires when an item is replaced in the collection.
42 * @param {String} key he key associated with the new added.
43 * @param {Object} old The item being replaced.
44 * @param {Object} new The new item.
49 * Fires when an item is removed from the collection.
50 * @param {Object} o The item being removed.
51 * @param {String} key (optional) The key associated with the removed item.
56 this.allowFunctions = allowFunctions === true;
60 Ext.util.MixedCollection.superclass.constructor.call(this);
63 Ext.extend(Ext.util.MixedCollection, Ext.util.Observable, {
66 * @cfg {Boolean} allowFunctions Specify <tt>true</tt> if the {@link #addAll}
67 * function should add function references to the collection. Defaults to
70 allowFunctions : false,
73 * Adds an item to the collection. Fires the {@link #add} event when complete.
74 * @param {String} key <p>The key to associate with the item, or the new item.</p>
75 * <p>If a {@link #getKey} implementation was specified for this MixedCollection,
76 * or if the key of the stored items is in a property called <tt><b>id</b></tt>,
77 * the MixedCollection will be able to <i>derive</i> the key for the new item.
78 * In this case just pass the new item in this parameter.</p>
79 * @param {Object} o The item to add.
80 * @return {Object} The item added.
82 add : function(key, o){
83 if(arguments.length == 1){
87 if(typeof key != 'undefined' && key !== null){
88 var old = this.map[key];
89 if(typeof old != 'undefined'){
90 return this.replace(key, o);
97 this.fireEvent('add', this.length-1, o, key);
102 * MixedCollection has a generic way to fetch keys if you implement getKey. The default implementation
103 * simply returns <b><code>item.id</code></b> but you can provide your own implementation
104 * to return a different value as in the following examples:<pre><code>
106 var mc = new Ext.util.MixedCollection();
107 mc.add(someEl.dom.id, someEl);
108 mc.add(otherEl.dom.id, otherEl);
112 var mc = new Ext.util.MixedCollection();
113 mc.getKey = function(el){
119 // or via the constructor
120 var mc = new Ext.util.MixedCollection(false, function(el){
126 * @param {Object} item The item for which to find the key.
127 * @return {Object} The key for the passed item.
129 getKey : function(o){
134 * Replaces an item in the collection. Fires the {@link #replace} event when complete.
135 * @param {String} key <p>The key associated with the item to replace, or the replacement item.</p>
136 * <p>If you supplied a {@link #getKey} implementation for this MixedCollection, or if the key
137 * of your stored items is in a property called <tt><b>id</b></tt>, then the MixedCollection
138 * will be able to <i>derive</i> the key of the replacement item. If you want to replace an item
139 * with one having the same key value, then just pass the replacement item in this parameter.</p>
140 * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate
142 * @return {Object} The new item.
144 replace : function(key, o){
145 if(arguments.length == 1){
147 key = this.getKey(o);
149 var old = this.map[key];
150 if(typeof key == 'undefined' || key === null || typeof old == 'undefined'){
151 return this.add(key, o);
153 var index = this.indexOfKey(key);
154 this.items[index] = o;
156 this.fireEvent('replace', key, old, o);
161 * Adds all elements of an Array or an Object to the collection.
162 * @param {Object/Array} objs An Object containing properties which will be added
163 * to the collection, or an Array of values, each of which are added to the collection.
164 * Functions references will be added to the collection if <code>{@link #allowFunctions}</code>
165 * has been set to <tt>true</tt>.
167 addAll : function(objs){
168 if(arguments.length > 1 || Ext.isArray(objs)){
169 var args = arguments.length > 1 ? arguments : objs;
170 for(var i = 0, len = args.length; i < len; i++){
174 for(var key in objs){
175 if(this.allowFunctions || typeof objs[key] != 'function'){
176 this.add(key, objs[key]);
183 * Executes the specified function once for every item in the collection, passing the following arguments:
184 * <div class="mdetail-params"><ul>
185 * <li><b>item</b> : Mixed<p class="sub-desc">The collection item</p></li>
186 * <li><b>index</b> : Number<p class="sub-desc">The item's index</p></li>
187 * <li><b>length</b> : Number<p class="sub-desc">The total number of items in the collection</p></li>
189 * The function should return a boolean value. Returning false from the function will stop the iteration.
190 * @param {Function} fn The function to execute for each item.
191 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the current item in the iteration.
193 each : function(fn, scope){
194 var items = [].concat(this.items); // each safe for removal
195 for(var i = 0, len = items.length; i < len; i++){
196 if(fn.call(scope || items[i], items[i], i, len) === false){
203 * Executes the specified function once for every key in the collection, passing each
204 * key, and its associated item as the first two parameters.
205 * @param {Function} fn The function to execute for each item.
206 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the browser window.
208 eachKey : function(fn, scope){
209 for(var i = 0, len = this.keys.length; i < len; i++){
210 fn.call(scope || window, this.keys[i], this.items[i], i, len);
215 * Returns the first item in the collection which elicits a true return value from the
216 * passed selection function.
217 * @param {Function} fn The selection function to execute for each item.
218 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the browser window.
219 * @return {Object} The first item in the collection which returned true from the selection function.
221 find : function(fn, scope){
222 for(var i = 0, len = this.items.length; i < len; i++){
223 if(fn.call(scope || window, this.items[i], this.keys[i])){
224 return this.items[i];
231 * Inserts an item at the specified index in the collection. Fires the {@link #add} event when complete.
232 * @param {Number} index The index to insert the item at.
233 * @param {String} key The key to associate with the new item, or the item itself.
234 * @param {Object} o (optional) If the second parameter was a key, the new item.
235 * @return {Object} The item inserted.
237 insert : function(index, key, o){
238 if(arguments.length == 2){
240 key = this.getKey(o);
242 if(this.containsKey(key)){
243 this.suspendEvents();
247 if(index >= this.length){
248 return this.add(key, o);
251 this.items.splice(index, 0, o);
252 if(typeof key != 'undefined' && key !== null){
255 this.keys.splice(index, 0, key);
256 this.fireEvent('add', index, o, key);
261 * Remove an item from the collection.
262 * @param {Object} o The item to remove.
263 * @return {Object} The item removed or false if no item was removed.
265 remove : function(o){
266 return this.removeAt(this.indexOf(o));
270 * Remove an item from a specified index in the collection. Fires the {@link #remove} event when complete.
271 * @param {Number} index The index within the collection of the item to remove.
272 * @return {Object} The item removed or false if no item was removed.
274 removeAt : function(index){
275 if(index < this.length && index >= 0){
277 var o = this.items[index];
278 this.items.splice(index, 1);
279 var key = this.keys[index];
280 if(typeof key != 'undefined'){
281 delete this.map[key];
283 this.keys.splice(index, 1);
284 this.fireEvent('remove', o, key);
291 * Removed an item associated with the passed key fom the collection.
292 * @param {String} key The key of the item to remove.
293 * @return {Object} The item removed or false if no item was removed.
295 removeKey : function(key){
296 return this.removeAt(this.indexOfKey(key));
300 * Returns the number of items in the collection.
301 * @return {Number} the number of items in the collection.
303 getCount : function(){
308 * Returns index within the collection of the passed Object.
309 * @param {Object} o The item to find the index of.
310 * @return {Number} index of the item. Returns -1 if not found.
312 indexOf : function(o){
313 return this.items.indexOf(o);
317 * Returns index within the collection of the passed key.
318 * @param {String} key The key to find the index of.
319 * @return {Number} index of the key.
321 indexOfKey : function(key){
322 return this.keys.indexOf(key);
326 * Returns the item associated with the passed key OR index.
327 * Key has priority over index. This is the equivalent
328 * of calling {@link #key} first, then if nothing matched calling {@link #itemAt}.
329 * @param {String/Number} key The key or index of the item.
330 * @return {Object} If the item is found, returns the item. If the item was not found, returns <tt>undefined</tt>.
331 * If an item was found, but is a Class, returns <tt>null</tt>.
333 item : function(key){
334 var mk = this.map[key],
335 item = mk !== undefined ? mk : (typeof key == 'number') ? this.items[key] : undefined;
336 return !Ext.isFunction(item) || this.allowFunctions ? item : null; // for prototype!
340 * Returns the item at the specified index.
341 * @param {Number} index The index of the item.
342 * @return {Object} The item at the specified index.
344 itemAt : function(index){
345 return this.items[index];
349 * Returns the item associated with the passed key.
350 * @param {String/Number} key The key of the item.
351 * @return {Object} The item associated with the passed key.
354 return this.map[key];
358 * Returns true if the collection contains the passed Object as an item.
359 * @param {Object} o The Object to look for in the collection.
360 * @return {Boolean} True if the collection contains the Object as an item.
362 contains : function(o){
363 return this.indexOf(o) != -1;
367 * Returns true if the collection contains the passed Object as a key.
368 * @param {String} key The key to look for in the collection.
369 * @return {Boolean} True if the collection contains the Object as a key.
371 containsKey : function(key){
372 return typeof this.map[key] != 'undefined';
376 * Removes all items from the collection. Fires the {@link #clear} event when complete.
383 this.fireEvent('clear');
387 * Returns the first item in the collection.
388 * @return {Object} the first item in the collection..
391 return this.items[0];
395 * Returns the last item in the collection.
396 * @return {Object} the last item in the collection..
399 return this.items[this.length-1];
404 * Performs the actual sorting based on a direction and a sorting function. Internally,
405 * this creates a temporary array of all items in the MixedCollection, sorts it and then writes
406 * the sorted array data back into this.items and this.keys
407 * @param {String} property Property to sort by ('key', 'value', or 'index')
408 * @param {String} dir (optional) Direction to sort 'ASC' or 'DESC'. Defaults to 'ASC'.
409 * @param {Function} fn (optional) Comparison function that defines the sort order.
410 * Defaults to sorting by numeric value.
412 _sort : function(property, dir, fn){
414 dsc = String(dir).toUpperCase() == 'DESC' ? -1 : 1,
416 //this is a temporary array used to apply the sorting function
421 //default to a simple sorter function if one is not provided
422 fn = fn || function(a, b) {
426 //copy all the items into a temporary array, which we will sort
427 for(i = 0, len = items.length; i < len; i++){
435 //sort the temporary array
436 c.sort(function(a, b){
437 var v = fn(a[property], b[property]) * dsc;
439 v = (a.index < b.index ? -1 : 1);
444 //copy the temporary array back into the main this.items and this.keys objects
445 for(i = 0, len = c.length; i < len; i++){
446 items[i] = c[i].value;
450 this.fireEvent('sort', this);
454 * Sorts this collection by <b>item</b> value with the passed comparison function.
455 * @param {String} direction (optional) 'ASC' or 'DESC'. Defaults to 'ASC'.
456 * @param {Function} fn (optional) Comparison function that defines the sort order.
457 * Defaults to sorting by numeric value.
459 sort : function(dir, fn){
460 this._sort('value', dir, fn);
464 * Reorders each of the items based on a mapping from old index to new index. Internally this
465 * just translates into a sort. The 'sort' event is fired whenever reordering has occured.
466 * @param {Object} mapping Mapping from old item index to new item index
468 reorder: function(mapping) {
469 this.suspendEvents();
471 var items = this.items,
473 length = items.length,
477 //object of {oldPosition: newPosition} reversed to {newPosition: oldPosition}
478 for (oldIndex in mapping) {
479 order[mapping[oldIndex]] = items[oldIndex];
482 for (index = 0; index < length; index++) {
483 if (mapping[index] == undefined) {
484 remaining.push(items[index]);
488 for (index = 0; index < length; index++) {
489 if (order[index] == undefined) {
490 order[index] = remaining.shift();
498 this.fireEvent('sort', this);
502 * Sorts this collection by <b>key</b>s.
503 * @param {String} direction (optional) 'ASC' or 'DESC'. Defaults to 'ASC'.
504 * @param {Function} fn (optional) Comparison function that defines the sort order.
505 * Defaults to sorting by case insensitive string.
507 keySort : function(dir, fn){
508 this._sort('key', dir, fn || function(a, b){
509 var v1 = String(a).toUpperCase(), v2 = String(b).toUpperCase();
510 return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
515 * Returns a range of items in this collection
516 * @param {Number} startIndex (optional) The starting index. Defaults to 0.
517 * @param {Number} endIndex (optional) The ending index. Defaults to the last item.
518 * @return {Array} An array of items
520 getRange : function(start, end){
521 var items = this.items;
522 if(items.length < 1){
526 end = Math.min(typeof end == 'undefined' ? this.length-1 : end, this.length-1);
529 for(i = start; i <= end; i++) {
530 r[r.length] = items[i];
533 for(i = start; i >= end; i--) {
534 r[r.length] = items[i];
541 * Filter the <i>objects</i> in this collection by a specific property.
542 * Returns a new collection that has been filtered.
543 * @param {String} property A property on your objects
544 * @param {String/RegExp} value Either string that the property values
545 * should start with or a RegExp to test against the property
546 * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
547 * @param {Boolean} caseSensitive (optional) True for case sensitive comparison (defaults to False).
548 * @return {MixedCollection} The new filtered collection
550 filter : function(property, value, anyMatch, caseSensitive){
551 if(Ext.isEmpty(value, false)){
554 value = this.createValueMatcher(value, anyMatch, caseSensitive);
555 return this.filterBy(function(o){
556 return o && value.test(o[property]);
561 * Filter by a function. Returns a <i>new</i> collection that has been filtered.
562 * The passed function will be called with each object in the collection.
563 * If the function returns true, the value is included otherwise it is filtered.
564 * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
565 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this MixedCollection.
566 * @return {MixedCollection} The new filtered collection
568 filterBy : function(fn, scope){
569 var r = new Ext.util.MixedCollection();
570 r.getKey = this.getKey;
571 var k = this.keys, it = this.items;
572 for(var i = 0, len = it.length; i < len; i++){
573 if(fn.call(scope||this, it[i], k[i])){
581 * Finds the index of the first matching object in this collection by a specific property/value.
582 * @param {String} property The name of a property on your objects.
583 * @param {String/RegExp} value A string that the property values
584 * should start with or a RegExp to test against the property.
585 * @param {Number} start (optional) The index to start searching at (defaults to 0).
586 * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning.
587 * @param {Boolean} caseSensitive (optional) True for case sensitive comparison.
588 * @return {Number} The matched index or -1
590 findIndex : function(property, value, start, anyMatch, caseSensitive){
591 if(Ext.isEmpty(value, false)){
594 value = this.createValueMatcher(value, anyMatch, caseSensitive);
595 return this.findIndexBy(function(o){
596 return o && value.test(o[property]);
601 * Find the index of the first matching object in this collection by a function.
602 * If the function returns <i>true</i> it is considered a match.
603 * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key).
604 * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this MixedCollection.
605 * @param {Number} start (optional) The index to start searching at (defaults to 0).
606 * @return {Number} The matched index or -1
608 findIndexBy : function(fn, scope, start){
609 var k = this.keys, it = this.items;
610 for(var i = (start||0), len = it.length; i < len; i++){
611 if(fn.call(scope||this, it[i], k[i])){
619 * Returns a regular expression based on the given value and matching options. This is used internally for finding and filtering,
620 * and by Ext.data.Store#filter
622 * @param {String} value The value to create the regex for. This is escaped using Ext.escapeRe
623 * @param {Boolean} anyMatch True to allow any match - no regex start/end line anchors will be added. Defaults to false
624 * @param {Boolean} caseSensitive True to make the regex case sensitive (adds 'i' switch to regex). Defaults to false.
625 * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false. Ignored if anyMatch is true.
627 createValueMatcher : function(value, anyMatch, caseSensitive, exactMatch) {
628 if (!value.exec) { // not a regex
629 var er = Ext.escapeRe;
630 value = String(value);
632 if (anyMatch === true) {
635 value = '^' + er(value);
636 if (exactMatch === true) {
640 value = new RegExp(value, caseSensitive ? '' : 'i');
646 * Creates a shallow copy of this collection
647 * @return {MixedCollection}
650 var r = new Ext.util.MixedCollection();
651 var k = this.keys, it = this.items;
652 for(var i = 0, len = it.length; i < len; i++){
655 r.getKey = this.getKey;
660 * This method calls {@link #item item()}.
661 * Returns the item associated with the passed key OR index. Key has priority
662 * over index. This is the equivalent of calling {@link #key} first, then if
663 * nothing matched calling {@link #itemAt}.
664 * @param {String/Number} key The key or index of the item.
665 * @return {Object} If the item is found, returns the item. If the item was
666 * not found, returns <tt>undefined</tt>. If an item was found, but is a Class,
667 * returns <tt>null</tt>.
669 Ext.util.MixedCollection.prototype.get = Ext.util.MixedCollection.prototype.item;