lib/goog/array/array.js

1// Copyright 2006 The Closure Library Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS-IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/**
16 * @fileoverview Utilities for manipulating arrays.
17 *
18 */
19
20
21goog.provide('goog.array');
22goog.provide('goog.array.ArrayLike');
23
24goog.require('goog.asserts');
25
26
27/**
28 * @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should
29 * rely on Array.prototype functions, if available.
30 *
31 * The Array.prototype functions can be defined by external libraries like
32 * Prototype and setting this flag to false forces closure to use its own
33 * goog.array implementation.
34 *
35 * If your javascript can be loaded by a third party site and you are wary about
36 * relying on the prototype functions, specify
37 * "--define goog.NATIVE_ARRAY_PROTOTYPES=false" to the JSCompiler.
38 *
39 * Setting goog.TRUSTED_SITE to false will automatically set
40 * NATIVE_ARRAY_PROTOTYPES to false.
41 */
42goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE);
43
44
45/**
46 * @define {boolean} If true, JSCompiler will use the native implementation of
47 * array functions where appropriate (e.g., {@code Array#filter}) and remove the
48 * unused pure JS implementation.
49 */
50goog.define('goog.array.ASSUME_NATIVE_FUNCTIONS', false);
51
52
53/**
54 * @typedef {Array|NodeList|Arguments|{length: number}}
55 */
56goog.array.ArrayLike;
57
58
59/**
60 * Returns the last element in an array without removing it.
61 * Same as goog.array.last.
62 * @param {Array.<T>|goog.array.ArrayLike} array The array.
63 * @return {T} Last item in array.
64 * @template T
65 */
66goog.array.peek = function(array) {
67 return array[array.length - 1];
68};
69
70
71/**
72 * Returns the last element in an array without removing it.
73 * Same as goog.array.peek.
74 * @param {Array.<T>|goog.array.ArrayLike} array The array.
75 * @return {T} Last item in array.
76 * @template T
77 */
78goog.array.last = goog.array.peek;
79
80
81/**
82 * Reference to the original {@code Array.prototype}.
83 * @private
84 */
85goog.array.ARRAY_PROTOTYPE_ = Array.prototype;
86
87
88// NOTE(arv): Since most of the array functions are generic it allows you to
89// pass an array-like object. Strings have a length and are considered array-
90// like. However, the 'in' operator does not work on strings so we cannot just
91// use the array path even if the browser supports indexing into strings. We
92// therefore end up splitting the string.
93
94
95/**
96 * Returns the index of the first element of an array with a specified value, or
97 * -1 if the element is not present in the array.
98 *
99 * See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}
100 *
101 * @param {Array.<T>|goog.array.ArrayLike} arr The array to be searched.
102 * @param {T} obj The object for which we are searching.
103 * @param {number=} opt_fromIndex The index at which to start the search. If
104 * omitted the search starts at index 0.
105 * @return {number} The index of the first matching array element.
106 * @template T
107 */
108goog.array.indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&
109 (goog.array.ASSUME_NATIVE_FUNCTIONS ||
110 goog.array.ARRAY_PROTOTYPE_.indexOf) ?
111 function(arr, obj, opt_fromIndex) {
112 goog.asserts.assert(arr.length != null);
113
114 return goog.array.ARRAY_PROTOTYPE_.indexOf.call(arr, obj, opt_fromIndex);
115 } :
116 function(arr, obj, opt_fromIndex) {
117 var fromIndex = opt_fromIndex == null ?
118 0 : (opt_fromIndex < 0 ?
119 Math.max(0, arr.length + opt_fromIndex) : opt_fromIndex);
120
121 if (goog.isString(arr)) {
122 // Array.prototype.indexOf uses === so only strings should be found.
123 if (!goog.isString(obj) || obj.length != 1) {
124 return -1;
125 }
126 return arr.indexOf(obj, fromIndex);
127 }
128
129 for (var i = fromIndex; i < arr.length; i++) {
130 if (i in arr && arr[i] === obj)
131 return i;
132 }
133 return -1;
134 };
135
136
137/**
138 * Returns the index of the last element of an array with a specified value, or
139 * -1 if the element is not present in the array.
140 *
141 * See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof}
142 *
143 * @param {!Array.<T>|!goog.array.ArrayLike} arr The array to be searched.
144 * @param {T} obj The object for which we are searching.
145 * @param {?number=} opt_fromIndex The index at which to start the search. If
146 * omitted the search starts at the end of the array.
147 * @return {number} The index of the last matching array element.
148 * @template T
149 */
150goog.array.lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&
151 (goog.array.ASSUME_NATIVE_FUNCTIONS ||
152 goog.array.ARRAY_PROTOTYPE_.lastIndexOf) ?
153 function(arr, obj, opt_fromIndex) {
154 goog.asserts.assert(arr.length != null);
155
156 // Firefox treats undefined and null as 0 in the fromIndex argument which
157 // leads it to always return -1
158 var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;
159 return goog.array.ARRAY_PROTOTYPE_.lastIndexOf.call(arr, obj, fromIndex);
160 } :
161 function(arr, obj, opt_fromIndex) {
162 var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;
163
164 if (fromIndex < 0) {
165 fromIndex = Math.max(0, arr.length + fromIndex);
166 }
167
168 if (goog.isString(arr)) {
169 // Array.prototype.lastIndexOf uses === so only strings should be found.
170 if (!goog.isString(obj) || obj.length != 1) {
171 return -1;
172 }
173 return arr.lastIndexOf(obj, fromIndex);
174 }
175
176 for (var i = fromIndex; i >= 0; i--) {
177 if (i in arr && arr[i] === obj)
178 return i;
179 }
180 return -1;
181 };
182
183
184/**
185 * Calls a function for each element in an array. Skips holes in the array.
186 * See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}
187 *
188 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array like object over
189 * which to iterate.
190 * @param {?function(this: S, T, number, ?): ?} f The function to call for every
191 * element. This function takes 3 arguments (the element, the index and the
192 * array). The return value is ignored.
193 * @param {S=} opt_obj The object to be used as the value of 'this' within f.
194 * @template T,S
195 */
196goog.array.forEach = goog.NATIVE_ARRAY_PROTOTYPES &&
197 (goog.array.ASSUME_NATIVE_FUNCTIONS ||
198 goog.array.ARRAY_PROTOTYPE_.forEach) ?
199 function(arr, f, opt_obj) {
200 goog.asserts.assert(arr.length != null);
201
202 goog.array.ARRAY_PROTOTYPE_.forEach.call(arr, f, opt_obj);
203 } :
204 function(arr, f, opt_obj) {
205 var l = arr.length; // must be fixed during loop... see docs
206 var arr2 = goog.isString(arr) ? arr.split('') : arr;
207 for (var i = 0; i < l; i++) {
208 if (i in arr2) {
209 f.call(opt_obj, arr2[i], i, arr);
210 }
211 }
212 };
213
214
215/**
216 * Calls a function for each element in an array, starting from the last
217 * element rather than the first.
218 *
219 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array
220 * like object over which to iterate.
221 * @param {?function(this: S, T, number, ?): ?} f The function to call for every
222 * element. This function
223 * takes 3 arguments (the element, the index and the array). The return
224 * value is ignored.
225 * @param {S=} opt_obj The object to be used as the value of 'this'
226 * within f.
227 * @template T,S
228 */
229goog.array.forEachRight = function(arr, f, opt_obj) {
230 var l = arr.length; // must be fixed during loop... see docs
231 var arr2 = goog.isString(arr) ? arr.split('') : arr;
232 for (var i = l - 1; i >= 0; --i) {
233 if (i in arr2) {
234 f.call(opt_obj, arr2[i], i, arr);
235 }
236 }
237};
238
239
240/**
241 * Calls a function for each element in an array, and if the function returns
242 * true adds the element to a new array.
243 *
244 * See {@link http://tinyurl.com/developer-mozilla-org-array-filter}
245 *
246 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array
247 * like object over which to iterate.
248 * @param {?function(this:S, T, number, ?):boolean} f The function to call for
249 * every element. This function
250 * takes 3 arguments (the element, the index and the array) and must
251 * return a Boolean. If the return value is true the element is added to the
252 * result array. If it is false the element is not included.
253 * @param {S=} opt_obj The object to be used as the value of 'this'
254 * within f.
255 * @return {!Array.<T>} a new array in which only elements that passed the test
256 * are present.
257 * @template T,S
258 */
259goog.array.filter = goog.NATIVE_ARRAY_PROTOTYPES &&
260 (goog.array.ASSUME_NATIVE_FUNCTIONS ||
261 goog.array.ARRAY_PROTOTYPE_.filter) ?
262 function(arr, f, opt_obj) {
263 goog.asserts.assert(arr.length != null);
264
265 return goog.array.ARRAY_PROTOTYPE_.filter.call(arr, f, opt_obj);
266 } :
267 function(arr, f, opt_obj) {
268 var l = arr.length; // must be fixed during loop... see docs
269 var res = [];
270 var resLength = 0;
271 var arr2 = goog.isString(arr) ? arr.split('') : arr;
272 for (var i = 0; i < l; i++) {
273 if (i in arr2) {
274 var val = arr2[i]; // in case f mutates arr2
275 if (f.call(opt_obj, val, i, arr)) {
276 res[resLength++] = val;
277 }
278 }
279 }
280 return res;
281 };
282
283
284/**
285 * Calls a function for each element in an array and inserts the result into a
286 * new array.
287 *
288 * See {@link http://tinyurl.com/developer-mozilla-org-array-map}
289 *
290 * @param {Array.<VALUE>|goog.array.ArrayLike} arr Array or array like object
291 * over which to iterate.
292 * @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call
293 * for every element. This function takes 3 arguments (the element,
294 * the index and the array) and should return something. The result will be
295 * inserted into a new array.
296 * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.
297 * @return {!Array.<RESULT>} a new array with the results from f.
298 * @template THIS, VALUE, RESULT
299 */
300goog.array.map = goog.NATIVE_ARRAY_PROTOTYPES &&
301 (goog.array.ASSUME_NATIVE_FUNCTIONS ||
302 goog.array.ARRAY_PROTOTYPE_.map) ?
303 function(arr, f, opt_obj) {
304 goog.asserts.assert(arr.length != null);
305
306 return goog.array.ARRAY_PROTOTYPE_.map.call(arr, f, opt_obj);
307 } :
308 function(arr, f, opt_obj) {
309 var l = arr.length; // must be fixed during loop... see docs
310 var res = new Array(l);
311 var arr2 = goog.isString(arr) ? arr.split('') : arr;
312 for (var i = 0; i < l; i++) {
313 if (i in arr2) {
314 res[i] = f.call(opt_obj, arr2[i], i, arr);
315 }
316 }
317 return res;
318 };
319
320
321/**
322 * Passes every element of an array into a function and accumulates the result.
323 *
324 * See {@link http://tinyurl.com/developer-mozilla-org-array-reduce}
325 *
326 * For example:
327 * var a = [1, 2, 3, 4];
328 * goog.array.reduce(a, function(r, v, i, arr) {return r + v;}, 0);
329 * returns 10
330 *
331 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array
332 * like object over which to iterate.
333 * @param {?function(this:S, R, T, number, ?) : R} f The function to call for
334 * every element. This function
335 * takes 4 arguments (the function's previous result or the initial value,
336 * the value of the current array element, the current array index, and the
337 * array itself)
338 * function(previousValue, currentValue, index, array).
339 * @param {?} val The initial value to pass into the function on the first call.
340 * @param {S=} opt_obj The object to be used as the value of 'this'
341 * within f.
342 * @return {R} Result of evaluating f repeatedly across the values of the array.
343 * @template T,S,R
344 */
345goog.array.reduce = goog.NATIVE_ARRAY_PROTOTYPES &&
346 (goog.array.ASSUME_NATIVE_FUNCTIONS ||
347 goog.array.ARRAY_PROTOTYPE_.reduce) ?
348 function(arr, f, val, opt_obj) {
349 goog.asserts.assert(arr.length != null);
350 if (opt_obj) {
351 f = goog.bind(f, opt_obj);
352 }
353 return goog.array.ARRAY_PROTOTYPE_.reduce.call(arr, f, val);
354 } :
355 function(arr, f, val, opt_obj) {
356 var rval = val;
357 goog.array.forEach(arr, function(val, index) {
358 rval = f.call(opt_obj, rval, val, index, arr);
359 });
360 return rval;
361 };
362
363
364/**
365 * Passes every element of an array into a function and accumulates the result,
366 * starting from the last element and working towards the first.
367 *
368 * See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright}
369 *
370 * For example:
371 * var a = ['a', 'b', 'c'];
372 * goog.array.reduceRight(a, function(r, v, i, arr) {return r + v;}, '');
373 * returns 'cba'
374 *
375 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array
376 * like object over which to iterate.
377 * @param {?function(this:S, R, T, number, ?) : R} f The function to call for
378 * every element. This function
379 * takes 4 arguments (the function's previous result or the initial value,
380 * the value of the current array element, the current array index, and the
381 * array itself)
382 * function(previousValue, currentValue, index, array).
383 * @param {?} val The initial value to pass into the function on the first call.
384 * @param {S=} opt_obj The object to be used as the value of 'this'
385 * within f.
386 * @return {R} Object returned as a result of evaluating f repeatedly across the
387 * values of the array.
388 * @template T,S,R
389 */
390goog.array.reduceRight = goog.NATIVE_ARRAY_PROTOTYPES &&
391 (goog.array.ASSUME_NATIVE_FUNCTIONS ||
392 goog.array.ARRAY_PROTOTYPE_.reduceRight) ?
393 function(arr, f, val, opt_obj) {
394 goog.asserts.assert(arr.length != null);
395 if (opt_obj) {
396 f = goog.bind(f, opt_obj);
397 }
398 return goog.array.ARRAY_PROTOTYPE_.reduceRight.call(arr, f, val);
399 } :
400 function(arr, f, val, opt_obj) {
401 var rval = val;
402 goog.array.forEachRight(arr, function(val, index) {
403 rval = f.call(opt_obj, rval, val, index, arr);
404 });
405 return rval;
406 };
407
408
409/**
410 * Calls f for each element of an array. If any call returns true, some()
411 * returns true (without checking the remaining elements). If all calls
412 * return false, some() returns false.
413 *
414 * See {@link http://tinyurl.com/developer-mozilla-org-array-some}
415 *
416 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array
417 * like object over which to iterate.
418 * @param {?function(this:S, T, number, ?) : boolean} f The function to call for
419 * for every element. This function takes 3 arguments (the element, the
420 * index and the array) and should return a boolean.
421 * @param {S=} opt_obj The object to be used as the value of 'this'
422 * within f.
423 * @return {boolean} true if any element passes the test.
424 * @template T,S
425 */
426goog.array.some = goog.NATIVE_ARRAY_PROTOTYPES &&
427 (goog.array.ASSUME_NATIVE_FUNCTIONS ||
428 goog.array.ARRAY_PROTOTYPE_.some) ?
429 function(arr, f, opt_obj) {
430 goog.asserts.assert(arr.length != null);
431
432 return goog.array.ARRAY_PROTOTYPE_.some.call(arr, f, opt_obj);
433 } :
434 function(arr, f, opt_obj) {
435 var l = arr.length; // must be fixed during loop... see docs
436 var arr2 = goog.isString(arr) ? arr.split('') : arr;
437 for (var i = 0; i < l; i++) {
438 if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) {
439 return true;
440 }
441 }
442 return false;
443 };
444
445
446/**
447 * Call f for each element of an array. If all calls return true, every()
448 * returns true. If any call returns false, every() returns false and
449 * does not continue to check the remaining elements.
450 *
451 * See {@link http://tinyurl.com/developer-mozilla-org-array-every}
452 *
453 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array
454 * like object over which to iterate.
455 * @param {?function(this:S, T, number, ?) : boolean} f The function to call for
456 * for every element. This function takes 3 arguments (the element, the
457 * index and the array) and should return a boolean.
458 * @param {S=} opt_obj The object to be used as the value of 'this'
459 * within f.
460 * @return {boolean} false if any element fails the test.
461 * @template T,S
462 */
463goog.array.every = goog.NATIVE_ARRAY_PROTOTYPES &&
464 (goog.array.ASSUME_NATIVE_FUNCTIONS ||
465 goog.array.ARRAY_PROTOTYPE_.every) ?
466 function(arr, f, opt_obj) {
467 goog.asserts.assert(arr.length != null);
468
469 return goog.array.ARRAY_PROTOTYPE_.every.call(arr, f, opt_obj);
470 } :
471 function(arr, f, opt_obj) {
472 var l = arr.length; // must be fixed during loop... see docs
473 var arr2 = goog.isString(arr) ? arr.split('') : arr;
474 for (var i = 0; i < l; i++) {
475 if (i in arr2 && !f.call(opt_obj, arr2[i], i, arr)) {
476 return false;
477 }
478 }
479 return true;
480 };
481
482
483/**
484 * Counts the array elements that fulfill the predicate, i.e. for which the
485 * callback function returns true. Skips holes in the array.
486 *
487 * @param {!(Array.<T>|goog.array.ArrayLike)} arr Array or array like object
488 * over which to iterate.
489 * @param {function(this: S, T, number, ?): boolean} f The function to call for
490 * every element. Takes 3 arguments (the element, the index and the array).
491 * @param {S=} opt_obj The object to be used as the value of 'this' within f.
492 * @return {number} The number of the matching elements.
493 * @template T,S
494 */
495goog.array.count = function(arr, f, opt_obj) {
496 var count = 0;
497 goog.array.forEach(arr, function(element, index, arr) {
498 if (f.call(opt_obj, element, index, arr)) {
499 ++count;
500 }
501 }, opt_obj);
502 return count;
503};
504
505
506/**
507 * Search an array for the first element that satisfies a given condition and
508 * return that element.
509 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array
510 * like object over which to iterate.
511 * @param {?function(this:S, T, number, ?) : boolean} f The function to call
512 * for every element. This function takes 3 arguments (the element, the
513 * index and the array) and should return a boolean.
514 * @param {S=} opt_obj An optional "this" context for the function.
515 * @return {?T} The first array element that passes the test, or null if no
516 * element is found.
517 * @template T,S
518 */
519goog.array.find = function(arr, f, opt_obj) {
520 var i = goog.array.findIndex(arr, f, opt_obj);
521 return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];
522};
523
524
525/**
526 * Search an array for the first element that satisfies a given condition and
527 * return its index.
528 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array
529 * like object over which to iterate.
530 * @param {?function(this:S, T, number, ?) : boolean} f The function to call for
531 * every element. This function
532 * takes 3 arguments (the element, the index and the array) and should
533 * return a boolean.
534 * @param {S=} opt_obj An optional "this" context for the function.
535 * @return {number} The index of the first array element that passes the test,
536 * or -1 if no element is found.
537 * @template T,S
538 */
539goog.array.findIndex = function(arr, f, opt_obj) {
540 var l = arr.length; // must be fixed during loop... see docs
541 var arr2 = goog.isString(arr) ? arr.split('') : arr;
542 for (var i = 0; i < l; i++) {
543 if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) {
544 return i;
545 }
546 }
547 return -1;
548};
549
550
551/**
552 * Search an array (in reverse order) for the last element that satisfies a
553 * given condition and return that element.
554 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array
555 * like object over which to iterate.
556 * @param {?function(this:S, T, number, ?) : boolean} f The function to call
557 * for every element. This function
558 * takes 3 arguments (the element, the index and the array) and should
559 * return a boolean.
560 * @param {S=} opt_obj An optional "this" context for the function.
561 * @return {?T} The last array element that passes the test, or null if no
562 * element is found.
563 * @template T,S
564 */
565goog.array.findRight = function(arr, f, opt_obj) {
566 var i = goog.array.findIndexRight(arr, f, opt_obj);
567 return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];
568};
569
570
571/**
572 * Search an array (in reverse order) for the last element that satisfies a
573 * given condition and return its index.
574 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array
575 * like object over which to iterate.
576 * @param {?function(this:S, T, number, ?) : boolean} f The function to call
577 * for every element. This function
578 * takes 3 arguments (the element, the index and the array) and should
579 * return a boolean.
580 * @param {Object=} opt_obj An optional "this" context for the function.
581 * @return {number} The index of the last array element that passes the test,
582 * or -1 if no element is found.
583 * @template T,S
584 */
585goog.array.findIndexRight = function(arr, f, opt_obj) {
586 var l = arr.length; // must be fixed during loop... see docs
587 var arr2 = goog.isString(arr) ? arr.split('') : arr;
588 for (var i = l - 1; i >= 0; i--) {
589 if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) {
590 return i;
591 }
592 }
593 return -1;
594};
595
596
597/**
598 * Whether the array contains the given object.
599 * @param {goog.array.ArrayLike} arr The array to test for the presence of the
600 * element.
601 * @param {*} obj The object for which to test.
602 * @return {boolean} true if obj is present.
603 */
604goog.array.contains = function(arr, obj) {
605 return goog.array.indexOf(arr, obj) >= 0;
606};
607
608
609/**
610 * Whether the array is empty.
611 * @param {goog.array.ArrayLike} arr The array to test.
612 * @return {boolean} true if empty.
613 */
614goog.array.isEmpty = function(arr) {
615 return arr.length == 0;
616};
617
618
619/**
620 * Clears the array.
621 * @param {goog.array.ArrayLike} arr Array or array like object to clear.
622 */
623goog.array.clear = function(arr) {
624 // For non real arrays we don't have the magic length so we delete the
625 // indices.
626 if (!goog.isArray(arr)) {
627 for (var i = arr.length - 1; i >= 0; i--) {
628 delete arr[i];
629 }
630 }
631 arr.length = 0;
632};
633
634
635/**
636 * Pushes an item into an array, if it's not already in the array.
637 * @param {Array.<T>} arr Array into which to insert the item.
638 * @param {T} obj Value to add.
639 * @template T
640 */
641goog.array.insert = function(arr, obj) {
642 if (!goog.array.contains(arr, obj)) {
643 arr.push(obj);
644 }
645};
646
647
648/**
649 * Inserts an object at the given index of the array.
650 * @param {goog.array.ArrayLike} arr The array to modify.
651 * @param {*} obj The object to insert.
652 * @param {number=} opt_i The index at which to insert the object. If omitted,
653 * treated as 0. A negative index is counted from the end of the array.
654 */
655goog.array.insertAt = function(arr, obj, opt_i) {
656 goog.array.splice(arr, opt_i, 0, obj);
657};
658
659
660/**
661 * Inserts at the given index of the array, all elements of another array.
662 * @param {goog.array.ArrayLike} arr The array to modify.
663 * @param {goog.array.ArrayLike} elementsToAdd The array of elements to add.
664 * @param {number=} opt_i The index at which to insert the object. If omitted,
665 * treated as 0. A negative index is counted from the end of the array.
666 */
667goog.array.insertArrayAt = function(arr, elementsToAdd, opt_i) {
668 goog.partial(goog.array.splice, arr, opt_i, 0).apply(null, elementsToAdd);
669};
670
671
672/**
673 * Inserts an object into an array before a specified object.
674 * @param {Array.<T>} arr The array to modify.
675 * @param {T} obj The object to insert.
676 * @param {T=} opt_obj2 The object before which obj should be inserted. If obj2
677 * is omitted or not found, obj is inserted at the end of the array.
678 * @template T
679 */
680goog.array.insertBefore = function(arr, obj, opt_obj2) {
681 var i;
682 if (arguments.length == 2 || (i = goog.array.indexOf(arr, opt_obj2)) < 0) {
683 arr.push(obj);
684 } else {
685 goog.array.insertAt(arr, obj, i);
686 }
687};
688
689
690/**
691 * Removes the first occurrence of a particular value from an array.
692 * @param {Array.<T>|goog.array.ArrayLike} arr Array from which to remove
693 * value.
694 * @param {T} obj Object to remove.
695 * @return {boolean} True if an element was removed.
696 * @template T
697 */
698goog.array.remove = function(arr, obj) {
699 var i = goog.array.indexOf(arr, obj);
700 var rv;
701 if ((rv = i >= 0)) {
702 goog.array.removeAt(arr, i);
703 }
704 return rv;
705};
706
707
708/**
709 * Removes from an array the element at index i
710 * @param {goog.array.ArrayLike} arr Array or array like object from which to
711 * remove value.
712 * @param {number} i The index to remove.
713 * @return {boolean} True if an element was removed.
714 */
715goog.array.removeAt = function(arr, i) {
716 goog.asserts.assert(arr.length != null);
717
718 // use generic form of splice
719 // splice returns the removed items and if successful the length of that
720 // will be 1
721 return goog.array.ARRAY_PROTOTYPE_.splice.call(arr, i, 1).length == 1;
722};
723
724
725/**
726 * Removes the first value that satisfies the given condition.
727 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array
728 * like object over which to iterate.
729 * @param {?function(this:S, T, number, ?) : boolean} f The function to call
730 * for every element. This function
731 * takes 3 arguments (the element, the index and the array) and should
732 * return a boolean.
733 * @param {S=} opt_obj An optional "this" context for the function.
734 * @return {boolean} True if an element was removed.
735 * @template T,S
736 */
737goog.array.removeIf = function(arr, f, opt_obj) {
738 var i = goog.array.findIndex(arr, f, opt_obj);
739 if (i >= 0) {
740 goog.array.removeAt(arr, i);
741 return true;
742 }
743 return false;
744};
745
746
747/**
748 * Removes all values that satisfy the given condition.
749 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array
750 * like object over which to iterate.
751 * @param {?function(this:S, T, number, ?) : boolean} f The function to call
752 * for every element. This function
753 * takes 3 arguments (the element, the index and the array) and should
754 * return a boolean.
755 * @param {S=} opt_obj An optional "this" context for the function.
756 * @return {number} The number of items removed
757 * @template T,S
758 */
759goog.array.removeAllIf = function(arr, f, opt_obj) {
760 var removedCount = 0;
761 goog.array.forEachRight(arr, function(val, index) {
762 if (f.call(opt_obj, val, index, arr)) {
763 if (goog.array.removeAt(arr, index)) {
764 removedCount++;
765 }
766 }
767 });
768 return removedCount;
769};
770
771
772/**
773 * Returns a new array that is the result of joining the arguments. If arrays
774 * are passed then their items are added, however, if non-arrays are passed they
775 * will be added to the return array as is.
776 *
777 * Note that ArrayLike objects will be added as is, rather than having their
778 * items added.
779 *
780 * goog.array.concat([1, 2], [3, 4]) -> [1, 2, 3, 4]
781 * goog.array.concat(0, [1, 2]) -> [0, 1, 2]
782 * goog.array.concat([1, 2], null) -> [1, 2, null]
783 *
784 * There is bug in all current versions of IE (6, 7 and 8) where arrays created
785 * in an iframe become corrupted soon (not immediately) after the iframe is
786 * destroyed. This is common if loading data via goog.net.IframeIo, for example.
787 * This corruption only affects the concat method which will start throwing
788 * Catastrophic Errors (#-2147418113).
789 *
790 * See http://endoflow.com/scratch/corrupted-arrays.html for a test case.
791 *
792 * Internally goog.array should use this, so that all methods will continue to
793 * work on these broken array objects.
794 *
795 * @param {...*} var_args Items to concatenate. Arrays will have each item
796 * added, while primitives and objects will be added as is.
797 * @return {!Array} The new resultant array.
798 */
799goog.array.concat = function(var_args) {
800 return goog.array.ARRAY_PROTOTYPE_.concat.apply(
801 goog.array.ARRAY_PROTOTYPE_, arguments);
802};
803
804
805/**
806 * Returns a new array that contains the contents of all the arrays passed.
807 * @param {...!Array.<T>} var_args
808 * @return {!Array.<T>}
809 * @template T
810 */
811goog.array.join = function(var_args) {
812 return goog.array.ARRAY_PROTOTYPE_.concat.apply(
813 goog.array.ARRAY_PROTOTYPE_, arguments);
814};
815
816
817/**
818 * Converts an object to an array.
819 * @param {Array.<T>|goog.array.ArrayLike} object The object to convert to an
820 * array.
821 * @return {!Array.<T>} The object converted into an array. If object has a
822 * length property, every property indexed with a non-negative number
823 * less than length will be included in the result. If object does not
824 * have a length property, an empty array will be returned.
825 * @template T
826 */
827goog.array.toArray = function(object) {
828 var length = object.length;
829
830 // If length is not a number the following it false. This case is kept for
831 // backwards compatibility since there are callers that pass objects that are
832 // not array like.
833 if (length > 0) {
834 var rv = new Array(length);
835 for (var i = 0; i < length; i++) {
836 rv[i] = object[i];
837 }
838 return rv;
839 }
840 return [];
841};
842
843
844/**
845 * Does a shallow copy of an array.
846 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array-like object to
847 * clone.
848 * @return {!Array.<T>} Clone of the input array.
849 * @template T
850 */
851goog.array.clone = goog.array.toArray;
852
853
854/**
855 * Extends an array with another array, element, or "array like" object.
856 * This function operates 'in-place', it does not create a new Array.
857 *
858 * Example:
859 * var a = [];
860 * goog.array.extend(a, [0, 1]);
861 * a; // [0, 1]
862 * goog.array.extend(a, 2);
863 * a; // [0, 1, 2]
864 *
865 * @param {Array.<VALUE>} arr1 The array to modify.
866 * @param {...(Array.<VALUE>|VALUE)} var_args The elements or arrays of elements
867 * to add to arr1.
868 * @template VALUE
869 */
870goog.array.extend = function(arr1, var_args) {
871 for (var i = 1; i < arguments.length; i++) {
872 var arr2 = arguments[i];
873 // If we have an Array or an Arguments object we can just call push
874 // directly.
875 var isArrayLike;
876 if (goog.isArray(arr2) ||
877 // Detect Arguments. ES5 says that the [[Class]] of an Arguments object
878 // is "Arguments" but only V8 and JSC/Safari gets this right. We instead
879 // detect Arguments by checking for array like and presence of "callee".
880 (isArrayLike = goog.isArrayLike(arr2)) &&
881 // The getter for callee throws an exception in strict mode
882 // according to section 10.6 in ES5 so check for presence instead.
883 Object.prototype.hasOwnProperty.call(arr2, 'callee')) {
884 arr1.push.apply(arr1, arr2);
885 } else if (isArrayLike) {
886 // Otherwise loop over arr2 to prevent copying the object.
887 var len1 = arr1.length;
888 var len2 = arr2.length;
889 for (var j = 0; j < len2; j++) {
890 arr1[len1 + j] = arr2[j];
891 }
892 } else {
893 arr1.push(arr2);
894 }
895 }
896};
897
898
899/**
900 * Adds or removes elements from an array. This is a generic version of Array
901 * splice. This means that it might work on other objects similar to arrays,
902 * such as the arguments object.
903 *
904 * @param {Array.<T>|goog.array.ArrayLike} arr The array to modify.
905 * @param {number|undefined} index The index at which to start changing the
906 * array. If not defined, treated as 0.
907 * @param {number} howMany How many elements to remove (0 means no removal. A
908 * value below 0 is treated as zero and so is any other non number. Numbers
909 * are floored).
910 * @param {...T} var_args Optional, additional elements to insert into the
911 * array.
912 * @return {!Array.<T>} the removed elements.
913 * @template T
914 */
915goog.array.splice = function(arr, index, howMany, var_args) {
916 goog.asserts.assert(arr.length != null);
917
918 return goog.array.ARRAY_PROTOTYPE_.splice.apply(
919 arr, goog.array.slice(arguments, 1));
920};
921
922
923/**
924 * Returns a new array from a segment of an array. This is a generic version of
925 * Array slice. This means that it might work on other objects similar to
926 * arrays, such as the arguments object.
927 *
928 * @param {Array.<T>|goog.array.ArrayLike} arr The array from
929 * which to copy a segment.
930 * @param {number} start The index of the first element to copy.
931 * @param {number=} opt_end The index after the last element to copy.
932 * @return {!Array.<T>} A new array containing the specified segment of the
933 * original array.
934 * @template T
935 */
936goog.array.slice = function(arr, start, opt_end) {
937 goog.asserts.assert(arr.length != null);
938
939 // passing 1 arg to slice is not the same as passing 2 where the second is
940 // null or undefined (in that case the second argument is treated as 0).
941 // we could use slice on the arguments object and then use apply instead of
942 // testing the length
943 if (arguments.length <= 2) {
944 return goog.array.ARRAY_PROTOTYPE_.slice.call(arr, start);
945 } else {
946 return goog.array.ARRAY_PROTOTYPE_.slice.call(arr, start, opt_end);
947 }
948};
949
950
951/**
952 * Removes all duplicates from an array (retaining only the first
953 * occurrence of each array element). This function modifies the
954 * array in place and doesn't change the order of the non-duplicate items.
955 *
956 * For objects, duplicates are identified as having the same unique ID as
957 * defined by {@link goog.getUid}.
958 *
959 * Alternatively you can specify a custom hash function that returns a unique
960 * value for each item in the array it should consider unique.
961 *
962 * Runtime: N,
963 * Worstcase space: 2N (no dupes)
964 *
965 * @param {Array.<T>|goog.array.ArrayLike} arr The array from which to remove
966 * duplicates.
967 * @param {Array=} opt_rv An optional array in which to return the results,
968 * instead of performing the removal inplace. If specified, the original
969 * array will remain unchanged.
970 * @param {function(T):string=} opt_hashFn An optional function to use to
971 * apply to every item in the array. This function should return a unique
972 * value for each item in the array it should consider unique.
973 * @template T
974 */
975goog.array.removeDuplicates = function(arr, opt_rv, opt_hashFn) {
976 var returnArray = opt_rv || arr;
977 var defaultHashFn = function(item) {
978 // Prefix each type with a single character representing the type to
979 // prevent conflicting keys (e.g. true and 'true').
980 return goog.isObject(current) ? 'o' + goog.getUid(current) :
981 (typeof current).charAt(0) + current;
982 };
983 var hashFn = opt_hashFn || defaultHashFn;
984
985 var seen = {}, cursorInsert = 0, cursorRead = 0;
986 while (cursorRead < arr.length) {
987 var current = arr[cursorRead++];
988 var key = hashFn(current);
989 if (!Object.prototype.hasOwnProperty.call(seen, key)) {
990 seen[key] = true;
991 returnArray[cursorInsert++] = current;
992 }
993 }
994 returnArray.length = cursorInsert;
995};
996
997
998/**
999 * Searches the specified array for the specified target using the binary
1000 * search algorithm. If no opt_compareFn is specified, elements are compared
1001 * using <code>goog.array.defaultCompare</code>, which compares the elements
1002 * using the built in < and > operators. This will produce the expected
1003 * behavior for homogeneous arrays of String(s) and Number(s). The array
1004 * specified <b>must</b> be sorted in ascending order (as defined by the
1005 * comparison function). If the array is not sorted, results are undefined.
1006 * If the array contains multiple instances of the specified target value, any
1007 * of these instances may be found.
1008 *
1009 * Runtime: O(log n)
1010 *
1011 * @param {Array.<VALUE>|goog.array.ArrayLike} arr The array to be searched.
1012 * @param {TARGET} target The sought value.
1013 * @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison
1014 * function by which the array is ordered. Should take 2 arguments to
1015 * compare, and return a negative number, zero, or a positive number
1016 * depending on whether the first argument is less than, equal to, or
1017 * greater than the second.
1018 * @return {number} Lowest index of the target value if found, otherwise
1019 * (-(insertion point) - 1). The insertion point is where the value should
1020 * be inserted into arr to preserve the sorted property. Return value >= 0
1021 * iff target is found.
1022 * @template TARGET, VALUE
1023 */
1024goog.array.binarySearch = function(arr, target, opt_compareFn) {
1025 return goog.array.binarySearch_(arr,
1026 opt_compareFn || goog.array.defaultCompare, false /* isEvaluator */,
1027 target);
1028};
1029
1030
1031/**
1032 * Selects an index in the specified array using the binary search algorithm.
1033 * The evaluator receives an element and determines whether the desired index
1034 * is before, at, or after it. The evaluator must be consistent (formally,
1035 * goog.array.map(goog.array.map(arr, evaluator, opt_obj), goog.math.sign)
1036 * must be monotonically non-increasing).
1037 *
1038 * Runtime: O(log n)
1039 *
1040 * @param {Array.<VALUE>|goog.array.ArrayLike} arr The array to be searched.
1041 * @param {function(this:THIS, VALUE, number, ?): number} evaluator
1042 * Evaluator function that receives 3 arguments (the element, the index and
1043 * the array). Should return a negative number, zero, or a positive number
1044 * depending on whether the desired index is before, at, or after the
1045 * element passed to it.
1046 * @param {THIS=} opt_obj The object to be used as the value of 'this'
1047 * within evaluator.
1048 * @return {number} Index of the leftmost element matched by the evaluator, if
1049 * such exists; otherwise (-(insertion point) - 1). The insertion point is
1050 * the index of the first element for which the evaluator returns negative,
1051 * or arr.length if no such element exists. The return value is non-negative
1052 * iff a match is found.
1053 * @template THIS, VALUE
1054 */
1055goog.array.binarySelect = function(arr, evaluator, opt_obj) {
1056 return goog.array.binarySearch_(arr, evaluator, true /* isEvaluator */,
1057 undefined /* opt_target */, opt_obj);
1058};
1059
1060
1061/**
1062 * Implementation of a binary search algorithm which knows how to use both
1063 * comparison functions and evaluators. If an evaluator is provided, will call
1064 * the evaluator with the given optional data object, conforming to the
1065 * interface defined in binarySelect. Otherwise, if a comparison function is
1066 * provided, will call the comparison function against the given data object.
1067 *
1068 * This implementation purposefully does not use goog.bind or goog.partial for
1069 * performance reasons.
1070 *
1071 * Runtime: O(log n)
1072 *
1073 * @param {Array.<VALUE>|goog.array.ArrayLike} arr The array to be searched.
1074 * @param {function(TARGET, VALUE): number|
1075 * function(this:THIS, VALUE, number, ?): number} compareFn Either an
1076 * evaluator or a comparison function, as defined by binarySearch
1077 * and binarySelect above.
1078 * @param {boolean} isEvaluator Whether the function is an evaluator or a
1079 * comparison function.
1080 * @param {TARGET=} opt_target If the function is a comparison function, then
1081 * this is the target to binary search for.
1082 * @param {THIS=} opt_selfObj If the function is an evaluator, this is an
1083 * optional this object for the evaluator.
1084 * @return {number} Lowest index of the target value if found, otherwise
1085 * (-(insertion point) - 1). The insertion point is where the value should
1086 * be inserted into arr to preserve the sorted property. Return value >= 0
1087 * iff target is found.
1088 * @template THIS, VALUE, TARGET
1089 * @private
1090 */
1091goog.array.binarySearch_ = function(arr, compareFn, isEvaluator, opt_target,
1092 opt_selfObj) {
1093 var left = 0; // inclusive
1094 var right = arr.length; // exclusive
1095 var found;
1096 while (left < right) {
1097 var middle = (left + right) >> 1;
1098 var compareResult;
1099 if (isEvaluator) {
1100 compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);
1101 } else {
1102 compareResult = compareFn(opt_target, arr[middle]);
1103 }
1104 if (compareResult > 0) {
1105 left = middle + 1;
1106 } else {
1107 right = middle;
1108 // We are looking for the lowest index so we can't return immediately.
1109 found = !compareResult;
1110 }
1111 }
1112 // left is the index if found, or the insertion point otherwise.
1113 // ~left is a shorthand for -left - 1.
1114 return found ? left : ~left;
1115};
1116
1117
1118/**
1119 * Sorts the specified array into ascending order. If no opt_compareFn is
1120 * specified, elements are compared using
1121 * <code>goog.array.defaultCompare</code>, which compares the elements using
1122 * the built in < and > operators. This will produce the expected behavior
1123 * for homogeneous arrays of String(s) and Number(s), unlike the native sort,
1124 * but will give unpredictable results for heterogenous lists of strings and
1125 * numbers with different numbers of digits.
1126 *
1127 * This sort is not guaranteed to be stable.
1128 *
1129 * Runtime: Same as <code>Array.prototype.sort</code>
1130 *
1131 * @param {Array.<T>} arr The array to be sorted.
1132 * @param {?function(T,T):number=} opt_compareFn Optional comparison
1133 * function by which the
1134 * array is to be ordered. Should take 2 arguments to compare, and return a
1135 * negative number, zero, or a positive number depending on whether the
1136 * first argument is less than, equal to, or greater than the second.
1137 * @template T
1138 */
1139goog.array.sort = function(arr, opt_compareFn) {
1140 // TODO(arv): Update type annotation since null is not accepted.
1141 arr.sort(opt_compareFn || goog.array.defaultCompare);
1142};
1143
1144
1145/**
1146 * Sorts the specified array into ascending order in a stable way. If no
1147 * opt_compareFn is specified, elements are compared using
1148 * <code>goog.array.defaultCompare</code>, which compares the elements using
1149 * the built in < and > operators. This will produce the expected behavior
1150 * for homogeneous arrays of String(s) and Number(s).
1151 *
1152 * Runtime: Same as <code>Array.prototype.sort</code>, plus an additional
1153 * O(n) overhead of copying the array twice.
1154 *
1155 * @param {Array.<T>} arr The array to be sorted.
1156 * @param {?function(T, T): number=} opt_compareFn Optional comparison function
1157 * by which the array is to be ordered. Should take 2 arguments to compare,
1158 * and return a negative number, zero, or a positive number depending on
1159 * whether the first argument is less than, equal to, or greater than the
1160 * second.
1161 * @template T
1162 */
1163goog.array.stableSort = function(arr, opt_compareFn) {
1164 for (var i = 0; i < arr.length; i++) {
1165 arr[i] = {index: i, value: arr[i]};
1166 }
1167 var valueCompareFn = opt_compareFn || goog.array.defaultCompare;
1168 function stableCompareFn(obj1, obj2) {
1169 return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;
1170 };
1171 goog.array.sort(arr, stableCompareFn);
1172 for (var i = 0; i < arr.length; i++) {
1173 arr[i] = arr[i].value;
1174 }
1175};
1176
1177
1178/**
1179 * Sorts an array of objects by the specified object key and compare
1180 * function. If no compare function is provided, the key values are
1181 * compared in ascending order using <code>goog.array.defaultCompare</code>.
1182 * This won't work for keys that get renamed by the compiler. So use
1183 * {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.
1184 * @param {Array.<Object>} arr An array of objects to sort.
1185 * @param {string} key The object key to sort by.
1186 * @param {Function=} opt_compareFn The function to use to compare key
1187 * values.
1188 */
1189goog.array.sortObjectsByKey = function(arr, key, opt_compareFn) {
1190 var compare = opt_compareFn || goog.array.defaultCompare;
1191 goog.array.sort(arr, function(a, b) {
1192 return compare(a[key], b[key]);
1193 });
1194};
1195
1196
1197/**
1198 * Tells if the array is sorted.
1199 * @param {!Array.<T>} arr The array.
1200 * @param {?function(T,T):number=} opt_compareFn Function to compare the
1201 * array elements.
1202 * Should take 2 arguments to compare, and return a negative number, zero,
1203 * or a positive number depending on whether the first argument is less
1204 * than, equal to, or greater than the second.
1205 * @param {boolean=} opt_strict If true no equal elements are allowed.
1206 * @return {boolean} Whether the array is sorted.
1207 * @template T
1208 */
1209goog.array.isSorted = function(arr, opt_compareFn, opt_strict) {
1210 var compare = opt_compareFn || goog.array.defaultCompare;
1211 for (var i = 1; i < arr.length; i++) {
1212 var compareResult = compare(arr[i - 1], arr[i]);
1213 if (compareResult > 0 || compareResult == 0 && opt_strict) {
1214 return false;
1215 }
1216 }
1217 return true;
1218};
1219
1220
1221/**
1222 * Compares two arrays for equality. Two arrays are considered equal if they
1223 * have the same length and their corresponding elements are equal according to
1224 * the comparison function.
1225 *
1226 * @param {goog.array.ArrayLike} arr1 The first array to compare.
1227 * @param {goog.array.ArrayLike} arr2 The second array to compare.
1228 * @param {Function=} opt_equalsFn Optional comparison function.
1229 * Should take 2 arguments to compare, and return true if the arguments
1230 * are equal. Defaults to {@link goog.array.defaultCompareEquality} which
1231 * compares the elements using the built-in '===' operator.
1232 * @return {boolean} Whether the two arrays are equal.
1233 */
1234goog.array.equals = function(arr1, arr2, opt_equalsFn) {
1235 if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||
1236 arr1.length != arr2.length) {
1237 return false;
1238 }
1239 var l = arr1.length;
1240 var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality;
1241 for (var i = 0; i < l; i++) {
1242 if (!equalsFn(arr1[i], arr2[i])) {
1243 return false;
1244 }
1245 }
1246 return true;
1247};
1248
1249
1250/**
1251 * 3-way array compare function.
1252 * @param {!Array.<VALUE>|!goog.array.ArrayLike} arr1 The first array to
1253 * compare.
1254 * @param {!Array.<VALUE>|!goog.array.ArrayLike} arr2 The second array to
1255 * compare.
1256 * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
1257 * function by which the array is to be ordered. Should take 2 arguments to
1258 * compare, and return a negative number, zero, or a positive number
1259 * depending on whether the first argument is less than, equal to, or
1260 * greater than the second.
1261 * @return {number} Negative number, zero, or a positive number depending on
1262 * whether the first argument is less than, equal to, or greater than the
1263 * second.
1264 * @template VALUE
1265 */
1266goog.array.compare3 = function(arr1, arr2, opt_compareFn) {
1267 var compare = opt_compareFn || goog.array.defaultCompare;
1268 var l = Math.min(arr1.length, arr2.length);
1269 for (var i = 0; i < l; i++) {
1270 var result = compare(arr1[i], arr2[i]);
1271 if (result != 0) {
1272 return result;
1273 }
1274 }
1275 return goog.array.defaultCompare(arr1.length, arr2.length);
1276};
1277
1278
1279/**
1280 * Compares its two arguments for order, using the built in < and >
1281 * operators.
1282 * @param {VALUE} a The first object to be compared.
1283 * @param {VALUE} b The second object to be compared.
1284 * @return {number} A negative number, zero, or a positive number as the first
1285 * argument is less than, equal to, or greater than the second.
1286 * @template VALUE
1287 */
1288goog.array.defaultCompare = function(a, b) {
1289 return a > b ? 1 : a < b ? -1 : 0;
1290};
1291
1292
1293/**
1294 * Compares its two arguments for equality, using the built in === operator.
1295 * @param {*} a The first object to compare.
1296 * @param {*} b The second object to compare.
1297 * @return {boolean} True if the two arguments are equal, false otherwise.
1298 */
1299goog.array.defaultCompareEquality = function(a, b) {
1300 return a === b;
1301};
1302
1303
1304/**
1305 * Inserts a value into a sorted array. The array is not modified if the
1306 * value is already present.
1307 * @param {Array.<VALUE>|goog.array.ArrayLike} array The array to modify.
1308 * @param {VALUE} value The object to insert.
1309 * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
1310 * function by which the array is ordered. Should take 2 arguments to
1311 * compare, and return a negative number, zero, or a positive number
1312 * depending on whether the first argument is less than, equal to, or
1313 * greater than the second.
1314 * @return {boolean} True if an element was inserted.
1315 * @template VALUE
1316 */
1317goog.array.binaryInsert = function(array, value, opt_compareFn) {
1318 var index = goog.array.binarySearch(array, value, opt_compareFn);
1319 if (index < 0) {
1320 goog.array.insertAt(array, value, -(index + 1));
1321 return true;
1322 }
1323 return false;
1324};
1325
1326
1327/**
1328 * Removes a value from a sorted array.
1329 * @param {!Array.<VALUE>|!goog.array.ArrayLike} array The array to modify.
1330 * @param {VALUE} value The object to remove.
1331 * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
1332 * function by which the array is ordered. Should take 2 arguments to
1333 * compare, and return a negative number, zero, or a positive number
1334 * depending on whether the first argument is less than, equal to, or
1335 * greater than the second.
1336 * @return {boolean} True if an element was removed.
1337 * @template VALUE
1338 */
1339goog.array.binaryRemove = function(array, value, opt_compareFn) {
1340 var index = goog.array.binarySearch(array, value, opt_compareFn);
1341 return (index >= 0) ? goog.array.removeAt(array, index) : false;
1342};
1343
1344
1345/**
1346 * Splits an array into disjoint buckets according to a splitting function.
1347 * @param {Array.<T>} array The array.
1348 * @param {function(this:S, T,number,Array.<T>):?} sorter Function to call for
1349 * every element. This takes 3 arguments (the element, the index and the
1350 * array) and must return a valid object key (a string, number, etc), or
1351 * undefined, if that object should not be placed in a bucket.
1352 * @param {S=} opt_obj The object to be used as the value of 'this' within
1353 * sorter.
1354 * @return {!Object} An object, with keys being all of the unique return values
1355 * of sorter, and values being arrays containing the items for
1356 * which the splitter returned that key.
1357 * @template T,S
1358 */
1359goog.array.bucket = function(array, sorter, opt_obj) {
1360 var buckets = {};
1361
1362 for (var i = 0; i < array.length; i++) {
1363 var value = array[i];
1364 var key = sorter.call(opt_obj, value, i, array);
1365 if (goog.isDef(key)) {
1366 // Push the value to the right bucket, creating it if necessary.
1367 var bucket = buckets[key] || (buckets[key] = []);
1368 bucket.push(value);
1369 }
1370 }
1371
1372 return buckets;
1373};
1374
1375
1376/**
1377 * Creates a new object built from the provided array and the key-generation
1378 * function.
1379 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array like object over
1380 * which to iterate whose elements will be the values in the new object.
1381 * @param {?function(this:S, T, number, ?) : string} keyFunc The function to
1382 * call for every element. This function takes 3 arguments (the element, the
1383 * index and the array) and should return a string that will be used as the
1384 * key for the element in the new object. If the function returns the same
1385 * key for more than one element, the value for that key is
1386 * implementation-defined.
1387 * @param {S=} opt_obj The object to be used as the value of 'this'
1388 * within keyFunc.
1389 * @return {!Object.<T>} The new object.
1390 * @template T,S
1391 */
1392goog.array.toObject = function(arr, keyFunc, opt_obj) {
1393 var ret = {};
1394 goog.array.forEach(arr, function(element, index) {
1395 ret[keyFunc.call(opt_obj, element, index, arr)] = element;
1396 });
1397 return ret;
1398};
1399
1400
1401/**
1402 * Creates a range of numbers in an arithmetic progression.
1403 *
1404 * Range takes 1, 2, or 3 arguments:
1405 * <pre>
1406 * range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]
1407 * range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]
1408 * range(-2, -5, -1) produces [-2, -3, -4]
1409 * range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.
1410 * </pre>
1411 *
1412 * @param {number} startOrEnd The starting value of the range if an end argument
1413 * is provided. Otherwise, the start value is 0, and this is the end value.
1414 * @param {number=} opt_end The optional end value of the range.
1415 * @param {number=} opt_step The step size between range values. Defaults to 1
1416 * if opt_step is undefined or 0.
1417 * @return {!Array.<number>} An array of numbers for the requested range. May be
1418 * an empty array if adding the step would not converge toward the end
1419 * value.
1420 */
1421goog.array.range = function(startOrEnd, opt_end, opt_step) {
1422 var array = [];
1423 var start = 0;
1424 var end = startOrEnd;
1425 var step = opt_step || 1;
1426 if (opt_end !== undefined) {
1427 start = startOrEnd;
1428 end = opt_end;
1429 }
1430
1431 if (step * (end - start) < 0) {
1432 // Sign mismatch: start + step will never reach the end value.
1433 return [];
1434 }
1435
1436 if (step > 0) {
1437 for (var i = start; i < end; i += step) {
1438 array.push(i);
1439 }
1440 } else {
1441 for (var i = start; i > end; i += step) {
1442 array.push(i);
1443 }
1444 }
1445 return array;
1446};
1447
1448
1449/**
1450 * Returns an array consisting of the given value repeated N times.
1451 *
1452 * @param {VALUE} value The value to repeat.
1453 * @param {number} n The repeat count.
1454 * @return {!Array.<VALUE>} An array with the repeated value.
1455 * @template VALUE
1456 */
1457goog.array.repeat = function(value, n) {
1458 var array = [];
1459 for (var i = 0; i < n; i++) {
1460 array[i] = value;
1461 }
1462 return array;
1463};
1464
1465
1466/**
1467 * Returns an array consisting of every argument with all arrays
1468 * expanded in-place recursively.
1469 *
1470 * @param {...*} var_args The values to flatten.
1471 * @return {!Array} An array containing the flattened values.
1472 */
1473goog.array.flatten = function(var_args) {
1474 var result = [];
1475 for (var i = 0; i < arguments.length; i++) {
1476 var element = arguments[i];
1477 if (goog.isArray(element)) {
1478 result.push.apply(result, goog.array.flatten.apply(null, element));
1479 } else {
1480 result.push(element);
1481 }
1482 }
1483 return result;
1484};
1485
1486
1487/**
1488 * Rotates an array in-place. After calling this method, the element at
1489 * index i will be the element previously at index (i - n) %
1490 * array.length, for all values of i between 0 and array.length - 1,
1491 * inclusive.
1492 *
1493 * For example, suppose list comprises [t, a, n, k, s]. After invoking
1494 * rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].
1495 *
1496 * @param {!Array.<T>} array The array to rotate.
1497 * @param {number} n The amount to rotate.
1498 * @return {!Array.<T>} The array.
1499 * @template T
1500 */
1501goog.array.rotate = function(array, n) {
1502 goog.asserts.assert(array.length != null);
1503
1504 if (array.length) {
1505 n %= array.length;
1506 if (n > 0) {
1507 goog.array.ARRAY_PROTOTYPE_.unshift.apply(array, array.splice(-n, n));
1508 } else if (n < 0) {
1509 goog.array.ARRAY_PROTOTYPE_.push.apply(array, array.splice(0, -n));
1510 }
1511 }
1512 return array;
1513};
1514
1515
1516/**
1517 * Moves one item of an array to a new position keeping the order of the rest
1518 * of the items. Example use case: keeping a list of JavaScript objects
1519 * synchronized with the corresponding list of DOM elements after one of the
1520 * elements has been dragged to a new position.
1521 * @param {!(Array|Arguments|{length:number})} arr The array to modify.
1522 * @param {number} fromIndex Index of the item to move between 0 and
1523 * {@code arr.length - 1}.
1524 * @param {number} toIndex Target index between 0 and {@code arr.length - 1}.
1525 */
1526goog.array.moveItem = function(arr, fromIndex, toIndex) {
1527 goog.asserts.assert(fromIndex >= 0 && fromIndex < arr.length);
1528 goog.asserts.assert(toIndex >= 0 && toIndex < arr.length);
1529 // Remove 1 item at fromIndex.
1530 var removedItems = goog.array.ARRAY_PROTOTYPE_.splice.call(arr, fromIndex, 1);
1531 // Insert the removed item at toIndex.
1532 goog.array.ARRAY_PROTOTYPE_.splice.call(arr, toIndex, 0, removedItems[0]);
1533 // We don't use goog.array.insertAt and goog.array.removeAt, because they're
1534 // significantly slower than splice.
1535};
1536
1537
1538/**
1539 * Creates a new array for which the element at position i is an array of the
1540 * ith element of the provided arrays. The returned array will only be as long
1541 * as the shortest array provided; additional values are ignored. For example,
1542 * the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].
1543 *
1544 * This is similar to the zip() function in Python. See {@link
1545 * http://docs.python.org/library/functions.html#zip}
1546 *
1547 * @param {...!goog.array.ArrayLike} var_args Arrays to be combined.
1548 * @return {!Array.<!Array>} A new array of arrays created from provided arrays.
1549 */
1550goog.array.zip = function(var_args) {
1551 if (!arguments.length) {
1552 return [];
1553 }
1554 var result = [];
1555 for (var i = 0; true; i++) {
1556 var value = [];
1557 for (var j = 0; j < arguments.length; j++) {
1558 var arr = arguments[j];
1559 // If i is larger than the array length, this is the shortest array.
1560 if (i >= arr.length) {
1561 return result;
1562 }
1563 value.push(arr[i]);
1564 }
1565 result.push(value);
1566 }
1567};
1568
1569
1570/**
1571 * Shuffles the values in the specified array using the Fisher-Yates in-place
1572 * shuffle (also known as the Knuth Shuffle). By default, calls Math.random()
1573 * and so resets the state of that random number generator. Similarly, may reset
1574 * the state of the any other specified random number generator.
1575 *
1576 * Runtime: O(n)
1577 *
1578 * @param {!Array} arr The array to be shuffled.
1579 * @param {function():number=} opt_randFn Optional random function to use for
1580 * shuffling.
1581 * Takes no arguments, and returns a random number on the interval [0, 1).
1582 * Defaults to Math.random() using JavaScript's built-in Math library.
1583 */
1584goog.array.shuffle = function(arr, opt_randFn) {
1585 var randFn = opt_randFn || Math.random;
1586
1587 for (var i = arr.length - 1; i > 0; i--) {
1588 // Choose a random array index in [0, i] (inclusive with i).
1589 var j = Math.floor(randFn() * (i + 1));
1590
1591 var tmp = arr[i];
1592 arr[i] = arr[j];
1593 arr[j] = tmp;
1594 }
1595};