]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - jssource/src_files/include/javascript/yui3/build/collection/array-extras.js
Release 6.5.0
[Github/sugarcrm.git] / jssource / src_files / include / javascript / yui3 / build / collection / array-extras.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' );