]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - jssource/src_files/include/javascript/yui3/build/collection/collection.js
Release 6.5.0
[Github/sugarcrm.git] / jssource / src_files / include / javascript / yui3 / build / collection / collection.js
1 /*
2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
5 version: 3.3.0
6 build: 3167
7 */
8 YUI.add('array-extras', function(Y) {
9
10 /**
11  * Collection utilities beyond what is provided in the YUI core
12  * @module collection
13  * @submodule array-extras
14  */
15
16 var L = Y.Lang, Native = Array.prototype, A = Y.Array;
17
18 /**
19  * Adds the following array utilities to the YUI instance
20  * (Y.Array).  This is in addition to the methods provided
21  * in the core.
22  * @class YUI~array~extras
23  */
24
25 /**
26  * Returns the index of the last item in the array that contains the specified
27  * value, or -1 if the value isn't found.
28  * @method Array.lastIndexOf
29  * @static
30  * @param {Array} a Array to search in.
31  * @param {any} val Value to search for.
32  * @param {Number} fromIndex (optional) Index at which to start searching
33  *   backwards. Defaults to the array's length - 1. If negative, it will be
34  *   taken as an offset from the end of the array. If the calculated index is
35  *   less than 0, the array will not be searched and -1 will be returned.
36  * @return {Number} Index of the item that contains the value, or -1 if not
37  *   found.
38  */
39 A.lastIndexOf = Native.lastIndexOf ?
40     function(a, val, fromIndex) {
41         // An undefined fromIndex is still considered a value by some (all?)
42         // native implementations, so we can't pass it unless it's actually
43         // specified.
44         return fromIndex || fromIndex === 0 ? a.lastIndexOf(val, fromIndex) :
45                 a.lastIndexOf(val);
46     } :
47     function(a, val, fromIndex) {
48         var len = a.length,
49             i   = len - 1;
50
51         if (fromIndex || fromIndex === 0) {
52             i = Math.min(fromIndex < 0 ? len + fromIndex : fromIndex, len);
53         }
54
55         if (i > -1 && len > 0) {
56             for (; i > -1; --i) {
57                 if (a[i] === val) {
58                     return i;
59                 }
60             }
61         }
62
63         return -1;
64     };
65
66 /**
67  * Returns a copy of the specified array with duplicate items removed.
68  * @method Array.unique
69  * @param {Array} a Array to dedupe.
70  * @return {Array} Copy of the array with duplicate items removed.
71  * @static
72  */
73 A.unique = function(a, sort) {
74     // Note: the sort param is deprecated and intentionally undocumented since
75     // YUI 3.3.0. It never did what the API docs said it did (see the older
76     // comment below as well).
77     var i       = 0,
78         len     = a.length,
79         results = [],
80         item, j;
81
82     for (; i < len; ++i) {
83         item = a[i];
84
85         // This loop iterates over the results array in reverse order and stops
86         // if it finds an item that matches the current input array item (a
87         // dupe). If it makes it all the way through without finding a dupe, the
88         // current item is pushed onto the results array.
89         for (j = results.length; j > -1; --j) {
90             if (item === results[j]) {
91                 break;
92             }
93         }
94
95         if (j === -1) {
96             results.push(item);
97         }
98     }
99
100     // Note: the sort option doesn't really belong here... I think it was added
101     // because there was a way to fast path the two operations together.  That
102     // implementation was not working, so I replaced it with the following.
103     // Leaving it in so that the API doesn't get broken.
104     if (sort) {
105         if (L.isNumber(results[0])) {
106             results.sort(A.numericSort);
107         } else {
108             results.sort();
109         }
110     }
111
112     return results;
113 };
114
115 /**
116 * Executes the supplied function on each item in the array. Returns a new array
117 * containing the items for which the supplied function returned a truthy value.
118 * @method Array.filter
119 * @param {Array} a Array to filter.
120 * @param {Function} f Function to execute on each item.
121 * @param {Object} o Optional context object.
122 * @static
123 * @return {Array} Array of items for which the supplied function returned a
124 *   truthy value (empty if it never returned a truthy value).
125 */
126 A.filter = Native.filter ?
127     function(a, f, o) {
128         return a.filter(f, o);
129     } :
130     function(a, f, o) {
131         var i       = 0,
132             len     = a.length,
133             results = [],
134             item;
135
136         for (; i < len; ++i) {
137             item = a[i];
138
139             if (f.call(o, item, i, a)) {
140                 results.push(item);
141             }
142         }
143
144         return results;
145     };
146
147 /**
148 * The inverse of filter. Executes the supplied function on each item.
149 * Returns a new array containing the items that the supplied
150 * function returned *false* for.
151 * @method Array.reject
152 * @param {Array} a the array to iterate.
153 * @param {Function} f the function to execute on each item.
154 * @param {object} o Optional context object.
155 * @static
156 * @return {Array} The items on which the supplied function
157 * returned false.
158 */
159 A.reject = function(a, f, o) {
160     return A.filter(a, function(item, i, a) {
161         return !f.call(o, item, i, a);
162     });
163 };
164
165 /**
166 * Executes the supplied function on each item in the array.
167 * Iteration stops if the supplied function does not return
168 * a truthy value.
169 * @method Array.every
170 * @param {Array} a the array to iterate.
171 * @param {Function} f the function to execute on each item.
172 * @param {object} o Optional context object.
173 * @static
174 * @return {boolean} true if every item in the array returns true
175 * from the supplied function.
176 */
177 A.every = Native.every ?
178     function(a, f, o) {
179         return a.every(f, o);
180     } :
181     function(a, f, o) {
182         for (var i = 0, l = a.length; i < l; ++i) {
183             if (!f.call(o, a[i], i, a)) {
184                 return false;
185             }
186         }
187
188         return true;
189     };
190
191 /**
192 * Executes the supplied function on each item in the array.
193 * @method Array.map
194 * @param {Array} a the array to iterate.
195 * @param {Function} f the function to execute on each item.
196 * @param {object} o Optional context object.
197 * @static
198 * @return {Array} A new array containing the return value
199 * of the supplied function for each item in the original
200 * array.
201 */
202 A.map = Native.map ?
203     function(a, f, o) {
204         return a.map(f, o);
205     } :
206     function(a, f, o) {
207         var i       = 0,
208             len     = a.length,
209             results = a.concat();
210
211         for (; i < len; ++i) {
212             results[i] = f.call(o, a[i], i, a);
213         }
214
215         return results;
216     };
217
218
219 /**
220 * Executes the supplied function on each item in the array.
221 * Reduce "folds" the array into a single value.  The callback
222 * function receives four arguments:
223 * the value from the previous callback call (or the initial value),
224 * the value of the current element, the current index, and
225 * the array over which iteration is occurring.
226 * @method Array.reduce
227 * @param {Array} a the array to iterate.
228 * @param {any} init The initial value to start from.
229 * @param {Function} f the function to execute on each item. It
230 * is responsible for returning the updated value of the
231 * computation.
232 * @param {object} o Optional context object.
233 * @static
234 * @return {any} A value that results from iteratively applying the
235 * supplied function to each element in the array.
236 */
237 A.reduce = Native.reduce ?
238     function(a, init, f, o) {
239         // ES5 Array.reduce doesn't support a thisObject, so we need to
240         // implement it manually
241         return a.reduce(function(init, item, i, a) {
242             return f.call(o, init, item, i, a);
243         }, init);
244     } :
245     function(a, init, f, o) {
246         var i      = 0,
247             len    = a.length,
248             result = init;
249
250         for (; i < len; ++i) {
251             result = f.call(o, result, a[i], i, a);
252         }
253
254         return result;
255     };
256
257
258 /**
259 * Executes the supplied function on each item in the array,
260 * searching for the first item that matches the supplied
261 * function.
262 * @method Array.find
263 * @param {Array} a the array to search.
264 * @param {Function} f the function to execute on each item.
265 * Iteration is stopped as soon as this function returns true
266 * on an item.
267 * @param {object} o Optional context object.
268 * @static
269 * @return {object} the first item that the supplied function
270 * returns true for, or null if it never returns true.
271 */
272 A.find = function(a, f, o) {
273     for (var i = 0, l = a.length; i < l; i++) {
274         if (f.call(o, a[i], i, a)) {
275             return a[i];
276         }
277     }
278     return null;
279 };
280
281 /**
282 * Iterates over an array, returning a new array of all the elements
283 * that match the supplied regular expression
284 * @method Array.grep
285 * @param {Array} a a collection to iterate over.
286 * @param {RegExp} pattern The regular expression to test against
287 * each item.
288 * @static
289 * @return {Array} All the items in the collection that
290 * produce a match against the supplied regular expression.
291 * If no items match, an empty array is returned.
292 */
293 A.grep = function(a, pattern) {
294     return A.filter(a, function(item, index) {
295         return pattern.test(item);
296     });
297 };
298
299
300 /**
301 * Partitions an array into two new arrays, one with the items
302 * that match the supplied function, and one with the items that
303 * do not.
304 * @method Array.partition
305 * @param {Array} a a collection to iterate over.
306 * @param {Function} f a function that will receive each item
307 * in the collection and its index.
308 * @param {object} o Optional execution context of f.
309 * @static
310 * @return {object} An object with two members, 'matches' and 'rejects',
311 * that are arrays containing the items that were selected or
312 * rejected by the test function (or an empty array).
313 */
314 A.partition = function(a, f, o) {
315     var results = {
316         matches: [],
317         rejects: []
318     };
319
320     A.each(a, function(item, index) {
321         var set = f.call(o, item, index, a) ? results.matches : results.rejects;
322         set.push(item);
323     });
324
325     return results;
326 };
327
328 /**
329 * Creates an array of arrays by pairing the corresponding
330 * elements of two arrays together into a new array.
331 * @method Array.zip
332 * @param {Array} a a collection to iterate over.
333 * @param {Array} a2 another collection whose members will be
334 * paired with members of the first parameter.
335 * @static
336 * @return {array} An array of arrays formed by pairing each element
337 * of the first collection with an item in the second collection
338 * having the corresponding index.
339 */
340 A.zip = function(a, a2) {
341     var results = [];
342     A.each(a, function(item, index) {
343         results.push([item, a2[index]]);
344     });
345     return results;
346 };
347
348 /**
349  * forEach is an alias of Array.each.  This is part of the
350  * collection module.
351  * @method Array.forEach
352  */
353 A.forEach = A.each;
354
355
356 }, '3.3.0' );
357 YUI.add('arraylist', function(Y) {
358
359 /**
360  * Collection utilities beyond what is provided in the YUI core
361  * @module collection
362  * @submodule arraylist
363  */
364
365 var YArray      = Y.Array,
366     YArray_each = YArray.each,
367     ArrayListProto;
368
369 /**
370  * Generic ArrayList class for managing lists of items and iterating operations
371  * over them.  The targeted use for this class is for augmentation onto a
372  * class that is responsible for managing multiple instances of another class
373  * (e.g. NodeList for Nodes).  The recommended use is to augment your class with
374  * ArrayList, then use ArrayList.addMethod to mirror the API of the constituent
375  * items on the list's API.
376  *
377  * The default implementation creates immutable lists, but mutability can be
378  * provided via the arraylist-add submodule or by implementing mutation methods
379  * directly on the augmented class's prototype.
380  *
381  * @class ArrayList
382  * @constructor
383  * @param items { Array } array of items this list will be responsible for
384  */
385 function ArrayList( items ) {
386     if ( items !== undefined ) {
387         this._items = Y.Lang.isArray( items ) ? items : YArray( items );
388     } else {
389         // ||= to support lazy initialization from augment
390         this._items = this._items || [];
391     }
392 }
393
394 ArrayListProto = {
395     /**
396      * Get an item by index from the list.  Override this method if managing a
397      * list of objects that have a different public representation (e.g. Node
398      * instances vs DOM nodes).  The iteration methods that accept a user
399      * function will use this method for access list items for operation.
400      *
401      * @method item
402      * @param i { Integer } index to fetch
403      * @return { mixed } the item at the requested index
404      */
405     item: function ( i ) {
406         return this._items[i];
407     },
408
409     /**
410      * <p>Execute a function on each item of the list, optionally providing a
411      * custom execution context.  Default context is the item.</p>
412      *
413      * <p>The callback signature is <code>callback( item, index )</code>.</p>
414      *
415      * @method each
416      * @param fn { Function } the function to execute
417      * @param context { mixed } optional override 'this' in the function
418      * @return { ArrayList } this instance
419      * @chainable
420      */
421     each: function ( fn, context ) {
422         YArray_each( this._items, function ( item, i ) {
423             item = this.item( i );
424
425             fn.call( context || item, item, i, this );
426         }, this);
427
428         return this;
429     },
430
431     /**
432      * <p>Execute a function on each item of the list, optionally providing a
433      * custom execution context.  Default context is the item.</p>
434      *
435      * <p>The callback signature is <code>callback( item, index )</code>.</p>
436      *
437      * <p>Unlike <code>each</code>, if the callback returns true, the
438      * iteratation will stop.</p>
439      *
440      * @method some
441      * @param fn { Function } the function to execute
442      * @param context { mixed } optional override 'this' in the function
443      * @return { Boolean } True if the function returned true on an item
444      */
445     some: function ( fn, context ) {
446         return YArray.some( this._items, function ( item, i ) {
447             item = this.item( i );
448
449             return fn.call( context || item, item, i, this );
450         }, this);
451     },
452
453     /**
454      * Finds the first index of the needle in the managed array of items.
455      *
456      * @method indexOf
457      * @param needle { mixed } The item to search for
458      * @return { Integer } Array index if found.  Otherwise -1
459      */
460     indexOf: function ( needle ) {
461         return YArray.indexOf( this._items, needle );
462     },
463
464     /**
465      * How many items are in this list?
466      *
467      * @method size
468      * @return { Integer } Number of items in the list
469      */
470     size: function () {
471         return this._items.length;
472     },
473
474     /**
475      * Is this instance managing any items?
476      *
477      * @method isEmpty
478      * @return { Boolean } true if 1 or more items are being managed
479      */
480     isEmpty: function () {
481         return !this.size();
482     },
483
484     /**
485      * Provides an array-like representation for JSON.stringify.
486      *
487      * @method toJSON
488      * @return { Array } an array representation of the ArrayList
489      */
490     toJSON: function () {
491         return this._items;
492     }
493 };
494 // Default implementation does not distinguish between public and private
495 // item getter
496 /**
497  * Protected method for optimizations that may be appropriate for API
498  * mirroring. Similar in functionality to <code>item</code>, but is used by
499  * methods added with <code>ArrayList.addMethod()</code>.
500  *
501  * @method _item
502  * @protected
503  * @param i { Integer } Index of item to fetch
504  * @return { mixed } The item appropriate for pass through API methods
505  */
506 ArrayListProto._item = ArrayListProto.item;
507
508 ArrayList.prototype  = ArrayListProto;
509
510 Y.mix( ArrayList, {
511
512     /**
513      * <p>Adds a pass through method to dest (typically the prototype of a list
514      * class) that calls the named method on each item in the list with
515      * whatever parameters are passed in.  Allows for API indirection via list
516      * instances.</p>
517      *
518      * <p>Accepts a single string name or an array of string names.</p>
519      *
520      * <pre><code>list.each( function ( item ) {
521      *     item.methodName( 1, 2, 3 );
522      * } );
523      * // becomes
524      * list.methodName( 1, 2, 3 );</code></pre>
525      *
526      * <p>Additionally, the pass through methods use the item retrieved by the
527      * <code>_item</code> method in case there is any special behavior that is
528      * appropriate for API mirroring.</p>
529      *
530      * @method addMethod
531      * @static
532      * @param dest { Object } Object or prototype to receive the iterator method
533      * @param name { String | Array } Name of method of methods to create
534      */
535     addMethod: function ( dest, names ) {
536
537         names = YArray( names );
538
539         YArray_each( names, function ( name ) {
540             dest[ name ] = function () {
541                 var args = YArray( arguments, 0, true ),
542                     ret  = [];
543
544                 YArray_each( this._items, function ( item, i ) {
545                     item = this._item( i );
546
547                     var result = item[ name ].apply( item, args );
548
549                     if ( result !== undefined && result !== item ) {
550                         ret.push( result );
551                     }
552                 }, this);
553
554                 return ret.length ? ret : this;
555             };
556         } );
557     }
558 } );
559
560 Y.ArrayList = ArrayList;
561
562
563 }, '3.3.0' );
564 YUI.add('arraylist-add', function(Y) {
565
566 /**
567  * Collection utilities beyond what is provided in the YUI core
568  * @module collection
569  * @submodule arraylist-add
570  */
571
572 /**
573  * Adds methods add and remove to Y.ArrayList
574  * @class ArrayList~add
575  */
576 Y.mix(Y.ArrayList.prototype, {
577
578     /**
579      * Add a single item to the ArrayList.  Does not prevent duplicates.
580      *
581      * @method add
582      * @param { mixed } item Item presumably of the same type as others in the
583      *                       ArrayList.
584      * @param {Number} index (Optional.)  Number representing the position at
585      * which the item should be inserted.
586      * @return {ArrayList} the instance.
587      * @chainable
588      */
589     add: function(item, index) {
590         var items = this._items;
591
592         if (Y.Lang.isNumber(index)) {
593             items.splice(index, 0, item);
594         }
595         else {
596             items.push(item);
597         }
598
599         return this;
600     },
601
602     /**
603      * Removes first or all occurrences of an item to the ArrayList.  If a
604      * comparator is not provided, uses itemsAreEqual method to determine
605      * matches.
606      *
607      * @method remove
608      * @param { mixed } needle Item to find and remove from the list.
609      * @param { Boolean } all If true, remove all occurrences.
610      * @param { Function } comparator optional a/b function to test equivalence.
611      * @return {ArrayList} the instance.
612      * @chainable
613      */
614     remove: function(needle, all, comparator) {
615         comparator = comparator || this.itemsAreEqual;
616
617         for (var i = this._items.length - 1; i >= 0; --i) {
618             if (comparator.call(this, needle, this.item(i))) {
619                 this._items.splice(i, 1);
620                 if (!all) {
621                     break;
622                 }
623             }
624         }
625
626         return this;
627     },
628
629     /**
630      * Default comparator for items stored in this list.  Used by remove().
631      *
632      * @method itemsAreEqual
633      * @param { mixed } a item to test equivalence with.
634      * @param { mixed } b other item to test equivalance.
635      * @return { Boolean } true if items are deemed equivalent.
636      */
637     itemsAreEqual: function(a, b) {
638         return a === b;
639     }
640
641 });
642
643
644 }, '3.3.0' ,{requires:['arraylist']});
645 YUI.add('arraylist-filter', function(Y) {
646
647 /**
648  * Collection utilities beyond what is provided in the YUI core
649  * @module collection
650  * @submodule arraylist-filter
651  */
652
653 /**
654  * Adds filter method to ArrayList prototype
655  * @class ArrayList~filter
656  */
657 Y.mix(Y.ArrayList.prototype, {
658
659     /**
660      * <p>Create a new ArrayList (or augmenting class instance) from a subset
661      * of items as determined by the boolean function passed as the
662      * argument.  The original ArrayList is unchanged.</p>
663      *
664      * <p>The validator signature is <code>validator( item )</code>.</p>
665      *
666      * @method filter
667      * @param { Function } validator Boolean function to determine in or out.
668      * @return { ArrayList } New instance based on who passed the validator.
669      */
670     filter: function(validator) {
671         var items = [];
672
673         Y.Array.each(this._items, function(item, i) {
674             item = this.item(i);
675
676             if (validator(item)) {
677                 items.push(item);
678             }
679         }, this);
680
681         return new this.constructor(items);
682     }
683
684 });
685
686
687 }, '3.3.0' ,{requires:['arraylist']});
688 YUI.add('array-invoke', function(Y) {
689
690 /**
691  * Collection utilities beyond what is provided in the YUI core
692  * @module collection
693  * @submodule array-invoke
694  */
695
696 /**
697  * Adds the <code>Y.Array.invoke( items, methodName )</code> utility method.
698  * @class YUI~array~invoke
699  */
700
701 /**
702  * <p>Execute a named method on an array of objects.  Items in the list that do
703  * not have a function by that name will be skipped. For example,
704  * <code>Y.Array.invoke( arrayOfDrags, 'plug', Y.Plugin.DDProxy );</code></p>
705  *
706  * <p>The return values from each call are returned in an array.</p>
707  *
708  * @method invoke
709  * @static
710  * @param { Array } items Array of objects supporting the named method.
711  * @param { String } name the name of the method to execute on each item.
712  * @param { mixed } args* Any number of additional args are passed as
713  *                        parameters to the execution of the named method.
714  * @return { Array } All return values, indexed according to item index.
715  */
716 Y.Array.invoke = function(items, name) {
717     var args = Y.Array(arguments, 2, true),
718         isFunction = Y.Lang.isFunction,
719         ret = [];
720
721     Y.Array.each(Y.Array(items), function(item, i) {
722         if (isFunction(item[name])) {
723             ret[i] = item[name].apply(item, args);
724         }
725     });
726
727     return ret;
728 };
729
730
731 }, '3.3.0' );
732
733
734 YUI.add('collection', function(Y){}, '3.3.0' ,{use:['array-extras', 'arraylist', 'arraylist-add', 'arraylist-filter', 'array-invoke']});
735