2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
8 YUI.add('array-extras', function(Y) {
11 * Collection utilities beyond what is provided in the YUI core
13 * @submodule array-extras
16 var L = Y.Lang, Native = Array.prototype, A = Y.Array;
19 * Adds the following array utilities to the YUI instance
20 * (Y.Array). This is in addition to the methods provided
22 * @class YUI~array~extras
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
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
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
44 return fromIndex || fromIndex === 0 ? a.lastIndexOf(val, fromIndex) :
47 function(a, val, fromIndex) {
51 if (fromIndex || fromIndex === 0) {
52 i = Math.min(fromIndex < 0 ? len + fromIndex : fromIndex, len);
55 if (i > -1 && len > 0) {
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.
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).
82 for (; i < len; ++i) {
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]) {
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.
105 if (L.isNumber(results[0])) {
106 results.sort(A.numericSort);
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.
123 * @return {Array} Array of items for which the supplied function returned a
124 * truthy value (empty if it never returned a truthy value).
126 A.filter = Native.filter ?
128 return a.filter(f, o);
136 for (; i < len; ++i) {
139 if (f.call(o, item, i, a)) {
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.
156 * @return {Array} The items on which the supplied function
159 A.reject = function(a, f, o) {
160 return A.filter(a, function(item, i, a) {
161 return !f.call(o, item, i, a);
166 * Executes the supplied function on each item in the array.
167 * Iteration stops if the supplied function does not return
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.
174 * @return {boolean} true if every item in the array returns true
175 * from the supplied function.
177 A.every = Native.every ?
179 return a.every(f, o);
182 for (var i = 0, l = a.length; i < l; ++i) {
183 if (!f.call(o, a[i], i, a)) {
192 * Executes the supplied function on each item in the array.
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.
198 * @return {Array} A new array containing the return value
199 * of the supplied function for each item in the original
209 results = a.concat();
211 for (; i < len; ++i) {
212 results[i] = f.call(o, a[i], i, a);
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
232 * @param {object} o Optional context object.
234 * @return {any} A value that results from iteratively applying the
235 * supplied function to each element in the array.
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);
245 function(a, init, f, o) {
250 for (; i < len; ++i) {
251 result = f.call(o, result, a[i], i, a);
259 * Executes the supplied function on each item in the array,
260 * searching for the first item that matches the supplied
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
267 * @param {object} o Optional context object.
269 * @return {object} the first item that the supplied function
270 * returns true for, or null if it never returns true.
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)) {
282 * Iterates over an array, returning a new array of all the elements
283 * that match the supplied regular expression
285 * @param {Array} a a collection to iterate over.
286 * @param {RegExp} pattern The regular expression to test against
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.
293 A.grep = function(a, pattern) {
294 return A.filter(a, function(item, index) {
295 return pattern.test(item);
301 * Partitions an array into two new arrays, one with the items
302 * that match the supplied function, and one with the items that
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.
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).
314 A.partition = function(a, f, o) {
320 A.each(a, function(item, index) {
321 var set = f.call(o, item, index, a) ? results.matches : results.rejects;
329 * Creates an array of arrays by pairing the corresponding
330 * elements of two arrays together into a new array.
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.
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.
340 A.zip = function(a, a2) {
342 A.each(a, function(item, index) {
343 results.push([item, a2[index]]);
349 * forEach is an alias of Array.each. This is part of the
351 * @method Array.forEach
357 YUI.add('arraylist', function(Y) {
360 * Collection utilities beyond what is provided in the YUI core
362 * @submodule arraylist
365 var YArray = Y.Array,
366 YArray_each = YArray.each,
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.
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.
383 * @param items { Array } array of items this list will be responsible for
385 function ArrayList( items ) {
386 if ( items !== undefined ) {
387 this._items = Y.Lang.isArray( items ) ? items : YArray( items );
389 // ||= to support lazy initialization from augment
390 this._items = this._items || [];
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.
402 * @param i { Integer } index to fetch
403 * @return { mixed } the item at the requested index
405 item: function ( i ) {
406 return this._items[i];
410 * <p>Execute a function on each item of the list, optionally providing a
411 * custom execution context. Default context is the item.</p>
413 * <p>The callback signature is <code>callback( item, index )</code>.</p>
416 * @param fn { Function } the function to execute
417 * @param context { mixed } optional override 'this' in the function
418 * @return { ArrayList } this instance
421 each: function ( fn, context ) {
422 YArray_each( this._items, function ( item, i ) {
423 item = this.item( i );
425 fn.call( context || item, item, i, this );
432 * <p>Execute a function on each item of the list, optionally providing a
433 * custom execution context. Default context is the item.</p>
435 * <p>The callback signature is <code>callback( item, index )</code>.</p>
437 * <p>Unlike <code>each</code>, if the callback returns true, the
438 * iteratation will stop.</p>
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
445 some: function ( fn, context ) {
446 return YArray.some( this._items, function ( item, i ) {
447 item = this.item( i );
449 return fn.call( context || item, item, i, this );
454 * Finds the first index of the needle in the managed array of items.
457 * @param needle { mixed } The item to search for
458 * @return { Integer } Array index if found. Otherwise -1
460 indexOf: function ( needle ) {
461 return YArray.indexOf( this._items, needle );
465 * How many items are in this list?
468 * @return { Integer } Number of items in the list
471 return this._items.length;
475 * Is this instance managing any items?
478 * @return { Boolean } true if 1 or more items are being managed
480 isEmpty: function () {
485 * Provides an array-like representation for JSON.stringify.
488 * @return { Array } an array representation of the ArrayList
490 toJSON: function () {
494 // Default implementation does not distinguish between public and private
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>.
503 * @param i { Integer } Index of item to fetch
504 * @return { mixed } The item appropriate for pass through API methods
506 ArrayListProto._item = ArrayListProto.item;
508 ArrayList.prototype = ArrayListProto;
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
518 * <p>Accepts a single string name or an array of string names.</p>
520 * <pre><code>list.each( function ( item ) {
521 * item.methodName( 1, 2, 3 );
524 * list.methodName( 1, 2, 3 );</code></pre>
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>
532 * @param dest { Object } Object or prototype to receive the iterator method
533 * @param name { String | Array } Name of method of methods to create
535 addMethod: function ( dest, names ) {
537 names = YArray( names );
539 YArray_each( names, function ( name ) {
540 dest[ name ] = function () {
541 var args = YArray( arguments, 0, true ),
544 YArray_each( this._items, function ( item, i ) {
545 item = this._item( i );
547 var result = item[ name ].apply( item, args );
549 if ( result !== undefined && result !== item ) {
554 return ret.length ? ret : this;
560 Y.ArrayList = ArrayList;
564 YUI.add('arraylist-add', function(Y) {
567 * Collection utilities beyond what is provided in the YUI core
569 * @submodule arraylist-add
573 * Adds methods add and remove to Y.ArrayList
574 * @class ArrayList~add
576 Y.mix(Y.ArrayList.prototype, {
579 * Add a single item to the ArrayList. Does not prevent duplicates.
582 * @param { mixed } item Item presumably of the same type as others in the
584 * @param {Number} index (Optional.) Number representing the position at
585 * which the item should be inserted.
586 * @return {ArrayList} the instance.
589 add: function(item, index) {
590 var items = this._items;
592 if (Y.Lang.isNumber(index)) {
593 items.splice(index, 0, item);
603 * Removes first or all occurrences of an item to the ArrayList. If a
604 * comparator is not provided, uses itemsAreEqual method to determine
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.
614 remove: function(needle, all, comparator) {
615 comparator = comparator || this.itemsAreEqual;
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);
630 * Default comparator for items stored in this list. Used by remove().
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.
637 itemsAreEqual: function(a, b) {
644 }, '3.3.0' ,{requires:['arraylist']});
645 YUI.add('arraylist-filter', function(Y) {
648 * Collection utilities beyond what is provided in the YUI core
650 * @submodule arraylist-filter
654 * Adds filter method to ArrayList prototype
655 * @class ArrayList~filter
657 Y.mix(Y.ArrayList.prototype, {
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>
664 * <p>The validator signature is <code>validator( item )</code>.</p>
667 * @param { Function } validator Boolean function to determine in or out.
668 * @return { ArrayList } New instance based on who passed the validator.
670 filter: function(validator) {
673 Y.Array.each(this._items, function(item, i) {
676 if (validator(item)) {
681 return new this.constructor(items);
687 }, '3.3.0' ,{requires:['arraylist']});
688 YUI.add('array-invoke', function(Y) {
691 * Collection utilities beyond what is provided in the YUI core
693 * @submodule array-invoke
697 * Adds the <code>Y.Array.invoke( items, methodName )</code> utility method.
698 * @class YUI~array~invoke
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>
706 * <p>The return values from each call are returned in an array.</p>
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.
716 Y.Array.invoke = function(items, name) {
717 var args = Y.Array(arguments, 2, true),
718 isFunction = Y.Lang.isFunction,
721 Y.Array.each(Y.Array(items), function(item, i) {
722 if (isFunction(item[name])) {
723 ret[i] = item[name].apply(item, args);
734 YUI.add('collection', function(Y){}, '3.3.0' ,{use:['array-extras', 'arraylist', 'arraylist-add', 'arraylist-filter', 'array-invoke']});