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 * Returns a new array that is the result of joining the arguments. If arrays
749 * are passed then their items are added, however, if non-arrays are passed they
750 * will be added to the return array as is.
751 *
752 * Note that ArrayLike objects will be added as is, rather than having their
753 * items added.
754 *
755 * goog.array.concat([1, 2], [3, 4]) -> [1, 2, 3, 4]
756 * goog.array.concat(0, [1, 2]) -> [0, 1, 2]
757 * goog.array.concat([1, 2], null) -> [1, 2, null]
758 *
759 * There is bug in all current versions of IE (6, 7 and 8) where arrays created
760 * in an iframe become corrupted soon (not immediately) after the iframe is
761 * destroyed. This is common if loading data via goog.net.IframeIo, for example.
762 * This corruption only affects the concat method which will start throwing
763 * Catastrophic Errors (#-2147418113).
764 *
765 * See http://endoflow.com/scratch/corrupted-arrays.html for a test case.
766 *
767 * Internally goog.array should use this, so that all methods will continue to
768 * work on these broken array objects.
769 *
770 * @param {...*} var_args Items to concatenate. Arrays will have each item
771 * added, while primitives and objects will be added as is.
772 * @return {!Array} The new resultant array.
773 */
774goog.array.concat = function(var_args) {
775 return goog.array.ARRAY_PROTOTYPE_.concat.apply(
776 goog.array.ARRAY_PROTOTYPE_, arguments);
777};
778
779
780/**
781 * Returns a new array that contains the contents of all the arrays passed.
782 * @param {...!Array.<T>} var_args
783 * @return {!Array.<T>}
784 * @template T
785 */
786goog.array.join = function(var_args) {
787 return goog.array.ARRAY_PROTOTYPE_.concat.apply(
788 goog.array.ARRAY_PROTOTYPE_, arguments);
789};
790
791
792/**
793 * Converts an object to an array.
794 * @param {Array.<T>|goog.array.ArrayLike} object The object to convert to an
795 * array.
796 * @return {!Array.<T>} The object converted into an array. If object has a
797 * length property, every property indexed with a non-negative number
798 * less than length will be included in the result. If object does not
799 * have a length property, an empty array will be returned.
800 * @template T
801 */
802goog.array.toArray = function(object) {
803 var length = object.length;
804
805 // If length is not a number the following it false. This case is kept for
806 // backwards compatibility since there are callers that pass objects that are
807 // not array like.
808 if (length > 0) {
809 var rv = new Array(length);
810 for (var i = 0; i < length; i++) {
811 rv[i] = object[i];
812 }
813 return rv;
814 }
815 return [];
816};
817
818
819/**
820 * Does a shallow copy of an array.
821 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array-like object to
822 * clone.
823 * @return {!Array.<T>} Clone of the input array.
824 * @template T
825 */
826goog.array.clone = goog.array.toArray;
827
828
829/**
830 * Extends an array with another array, element, or "array like" object.
831 * This function operates 'in-place', it does not create a new Array.
832 *
833 * Example:
834 * var a = [];
835 * goog.array.extend(a, [0, 1]);
836 * a; // [0, 1]
837 * goog.array.extend(a, 2);
838 * a; // [0, 1, 2]
839 *
840 * @param {Array.<VALUE>} arr1 The array to modify.
841 * @param {...(Array.<VALUE>|VALUE)} var_args The elements or arrays of elements
842 * to add to arr1.
843 * @template VALUE
844 */
845goog.array.extend = function(arr1, var_args) {
846 for (var i = 1; i < arguments.length; i++) {
847 var arr2 = arguments[i];
848 // If we have an Array or an Arguments object we can just call push
849 // directly.
850 var isArrayLike;
851 if (goog.isArray(arr2) ||
852 // Detect Arguments. ES5 says that the [[Class]] of an Arguments object
853 // is "Arguments" but only V8 and JSC/Safari gets this right. We instead
854 // detect Arguments by checking for array like and presence of "callee".
855 (isArrayLike = goog.isArrayLike(arr2)) &&
856 // The getter for callee throws an exception in strict mode
857 // according to section 10.6 in ES5 so check for presence instead.
858 Object.prototype.hasOwnProperty.call(arr2, 'callee')) {
859 arr1.push.apply(arr1, arr2);
860 } else if (isArrayLike) {
861 // Otherwise loop over arr2 to prevent copying the object.
862 var len1 = arr1.length;
863 var len2 = arr2.length;
864 for (var j = 0; j < len2; j++) {
865 arr1[len1 + j] = arr2[j];
866 }
867 } else {
868 arr1.push(arr2);
869 }
870 }
871};
872
873
874/**
875 * Adds or removes elements from an array. This is a generic version of Array
876 * splice. This means that it might work on other objects similar to arrays,
877 * such as the arguments object.
878 *
879 * @param {Array.<T>|goog.array.ArrayLike} arr The array to modify.
880 * @param {number|undefined} index The index at which to start changing the
881 * array. If not defined, treated as 0.
882 * @param {number} howMany How many elements to remove (0 means no removal. A
883 * value below 0 is treated as zero and so is any other non number. Numbers
884 * are floored).
885 * @param {...T} var_args Optional, additional elements to insert into the
886 * array.
887 * @return {!Array.<T>} the removed elements.
888 * @template T
889 */
890goog.array.splice = function(arr, index, howMany, var_args) {
891 goog.asserts.assert(arr.length != null);
892
893 return goog.array.ARRAY_PROTOTYPE_.splice.apply(
894 arr, goog.array.slice(arguments, 1));
895};
896
897
898/**
899 * Returns a new array from a segment of an array. This is a generic version of
900 * Array slice. This means that it might work on other objects similar to
901 * arrays, such as the arguments object.
902 *
903 * @param {Array.<T>|goog.array.ArrayLike} arr The array from
904 * which to copy a segment.
905 * @param {number} start The index of the first element to copy.
906 * @param {number=} opt_end The index after the last element to copy.
907 * @return {!Array.<T>} A new array containing the specified segment of the
908 * original array.
909 * @template T
910 */
911goog.array.slice = function(arr, start, opt_end) {
912 goog.asserts.assert(arr.length != null);
913
914 // passing 1 arg to slice is not the same as passing 2 where the second is
915 // null or undefined (in that case the second argument is treated as 0).
916 // we could use slice on the arguments object and then use apply instead of
917 // testing the length
918 if (arguments.length <= 2) {
919 return goog.array.ARRAY_PROTOTYPE_.slice.call(arr, start);
920 } else {
921 return goog.array.ARRAY_PROTOTYPE_.slice.call(arr, start, opt_end);
922 }
923};
924
925
926/**
927 * Removes all duplicates from an array (retaining only the first
928 * occurrence of each array element). This function modifies the
929 * array in place and doesn't change the order of the non-duplicate items.
930 *
931 * For objects, duplicates are identified as having the same unique ID as
932 * defined by {@link goog.getUid}.
933 *
934 * Alternatively you can specify a custom hash function that returns a unique
935 * value for each item in the array it should consider unique.
936 *
937 * Runtime: N,
938 * Worstcase space: 2N (no dupes)
939 *
940 * @param {Array.<T>|goog.array.ArrayLike} arr The array from which to remove
941 * duplicates.
942 * @param {Array=} opt_rv An optional array in which to return the results,
943 * instead of performing the removal inplace. If specified, the original
944 * array will remain unchanged.
945 * @param {function(T):string=} opt_hashFn An optional function to use to
946 * apply to every item in the array. This function should return a unique
947 * value for each item in the array it should consider unique.
948 * @template T
949 */
950goog.array.removeDuplicates = function(arr, opt_rv, opt_hashFn) {
951 var returnArray = opt_rv || arr;
952 var defaultHashFn = function(item) {
953 // Prefix each type with a single character representing the type to
954 // prevent conflicting keys (e.g. true and 'true').
955 return goog.isObject(current) ? 'o' + goog.getUid(current) :
956 (typeof current).charAt(0) + current;
957 };
958 var hashFn = opt_hashFn || defaultHashFn;
959
960 var seen = {}, cursorInsert = 0, cursorRead = 0;
961 while (cursorRead < arr.length) {
962 var current = arr[cursorRead++];
963 var key = hashFn(current);
964 if (!Object.prototype.hasOwnProperty.call(seen, key)) {
965 seen[key] = true;
966 returnArray[cursorInsert++] = current;
967 }
968 }
969 returnArray.length = cursorInsert;
970};
971
972
973/**
974 * Searches the specified array for the specified target using the binary
975 * search algorithm. If no opt_compareFn is specified, elements are compared
976 * using <code>goog.array.defaultCompare</code>, which compares the elements
977 * using the built in < and > operators. This will produce the expected
978 * behavior for homogeneous arrays of String(s) and Number(s). The array
979 * specified <b>must</b> be sorted in ascending order (as defined by the
980 * comparison function). If the array is not sorted, results are undefined.
981 * If the array contains multiple instances of the specified target value, any
982 * of these instances may be found.
983 *
984 * Runtime: O(log n)
985 *
986 * @param {Array.<VALUE>|goog.array.ArrayLike} arr The array to be searched.
987 * @param {TARGET} target The sought value.
988 * @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison
989 * function by which the array is ordered. Should take 2 arguments to
990 * compare, and return a negative number, zero, or a positive number
991 * depending on whether the first argument is less than, equal to, or
992 * greater than the second.
993 * @return {number} Lowest index of the target value if found, otherwise
994 * (-(insertion point) - 1). The insertion point is where the value should
995 * be inserted into arr to preserve the sorted property. Return value >= 0
996 * iff target is found.
997 * @template TARGET, VALUE
998 */
999goog.array.binarySearch = function(arr, target, opt_compareFn) {
1000 return goog.array.binarySearch_(arr,
1001 opt_compareFn || goog.array.defaultCompare, false /* isEvaluator */,
1002 target);
1003};
1004
1005
1006/**
1007 * Selects an index in the specified array using the binary search algorithm.
1008 * The evaluator receives an element and determines whether the desired index
1009 * is before, at, or after it. The evaluator must be consistent (formally,
1010 * goog.array.map(goog.array.map(arr, evaluator, opt_obj), goog.math.sign)
1011 * must be monotonically non-increasing).
1012 *
1013 * Runtime: O(log n)
1014 *
1015 * @param {Array.<VALUE>|goog.array.ArrayLike} arr The array to be searched.
1016 * @param {function(this:THIS, VALUE, number, ?): number} evaluator
1017 * Evaluator function that receives 3 arguments (the element, the index and
1018 * the array). Should return a negative number, zero, or a positive number
1019 * depending on whether the desired index is before, at, or after the
1020 * element passed to it.
1021 * @param {THIS=} opt_obj The object to be used as the value of 'this'
1022 * within evaluator.
1023 * @return {number} Index of the leftmost element matched by the evaluator, if
1024 * such exists; otherwise (-(insertion point) - 1). The insertion point is
1025 * the index of the first element for which the evaluator returns negative,
1026 * or arr.length if no such element exists. The return value is non-negative
1027 * iff a match is found.
1028 * @template THIS, VALUE
1029 */
1030goog.array.binarySelect = function(arr, evaluator, opt_obj) {
1031 return goog.array.binarySearch_(arr, evaluator, true /* isEvaluator */,
1032 undefined /* opt_target */, opt_obj);
1033};
1034
1035
1036/**
1037 * Implementation of a binary search algorithm which knows how to use both
1038 * comparison functions and evaluators. If an evaluator is provided, will call
1039 * the evaluator with the given optional data object, conforming to the
1040 * interface defined in binarySelect. Otherwise, if a comparison function is
1041 * provided, will call the comparison function against the given data object.
1042 *
1043 * This implementation purposefully does not use goog.bind or goog.partial for
1044 * performance reasons.
1045 *
1046 * Runtime: O(log n)
1047 *
1048 * @param {Array.<VALUE>|goog.array.ArrayLike} arr The array to be searched.
1049 * @param {function(TARGET, VALUE): number|
1050 * function(this:THIS, VALUE, number, ?): number} compareFn Either an
1051 * evaluator or a comparison function, as defined by binarySearch
1052 * and binarySelect above.
1053 * @param {boolean} isEvaluator Whether the function is an evaluator or a
1054 * comparison function.
1055 * @param {TARGET=} opt_target If the function is a comparison function, then
1056 * this is the target to binary search for.
1057 * @param {THIS=} opt_selfObj If the function is an evaluator, this is an
1058 * optional this object for the evaluator.
1059 * @return {number} Lowest index of the target value if found, otherwise
1060 * (-(insertion point) - 1). The insertion point is where the value should
1061 * be inserted into arr to preserve the sorted property. Return value >= 0
1062 * iff target is found.
1063 * @template THIS, VALUE, TARGET
1064 * @private
1065 */
1066goog.array.binarySearch_ = function(arr, compareFn, isEvaluator, opt_target,
1067 opt_selfObj) {
1068 var left = 0; // inclusive
1069 var right = arr.length; // exclusive
1070 var found;
1071 while (left < right) {
1072 var middle = (left + right) >> 1;
1073 var compareResult;
1074 if (isEvaluator) {
1075 compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);
1076 } else {
1077 compareResult = compareFn(opt_target, arr[middle]);
1078 }
1079 if (compareResult > 0) {
1080 left = middle + 1;
1081 } else {
1082 right = middle;
1083 // We are looking for the lowest index so we can't return immediately.
1084 found = !compareResult;
1085 }
1086 }
1087 // left is the index if found, or the insertion point otherwise.
1088 // ~left is a shorthand for -left - 1.
1089 return found ? left : ~left;
1090};
1091
1092
1093/**
1094 * Sorts the specified array into ascending order. If no opt_compareFn is
1095 * specified, elements are compared using
1096 * <code>goog.array.defaultCompare</code>, which compares the elements using
1097 * the built in < and > operators. This will produce the expected behavior
1098 * for homogeneous arrays of String(s) and Number(s), unlike the native sort,
1099 * but will give unpredictable results for heterogenous lists of strings and
1100 * numbers with different numbers of digits.
1101 *
1102 * This sort is not guaranteed to be stable.
1103 *
1104 * Runtime: Same as <code>Array.prototype.sort</code>
1105 *
1106 * @param {Array.<T>} arr The array to be sorted.
1107 * @param {?function(T,T):number=} opt_compareFn Optional comparison
1108 * function by which the
1109 * array is to be ordered. Should take 2 arguments to compare, and return a
1110 * negative number, zero, or a positive number depending on whether the
1111 * first argument is less than, equal to, or greater than the second.
1112 * @template T
1113 */
1114goog.array.sort = function(arr, opt_compareFn) {
1115 // TODO(arv): Update type annotation since null is not accepted.
1116 arr.sort(opt_compareFn || goog.array.defaultCompare);
1117};
1118
1119
1120/**
1121 * Sorts the specified array into ascending order in a stable way. If no
1122 * opt_compareFn is specified, elements are compared using
1123 * <code>goog.array.defaultCompare</code>, which compares the elements using
1124 * the built in < and > operators. This will produce the expected behavior
1125 * for homogeneous arrays of String(s) and Number(s).
1126 *
1127 * Runtime: Same as <code>Array.prototype.sort</code>, plus an additional
1128 * O(n) overhead of copying the array twice.
1129 *
1130 * @param {Array.<T>} arr The array to be sorted.
1131 * @param {?function(T, T): number=} opt_compareFn Optional comparison function
1132 * by which the array is to be ordered. Should take 2 arguments to compare,
1133 * and return a negative number, zero, or a positive number depending on
1134 * whether the first argument is less than, equal to, or greater than the
1135 * second.
1136 * @template T
1137 */
1138goog.array.stableSort = function(arr, opt_compareFn) {
1139 for (var i = 0; i < arr.length; i++) {
1140 arr[i] = {index: i, value: arr[i]};
1141 }
1142 var valueCompareFn = opt_compareFn || goog.array.defaultCompare;
1143 function stableCompareFn(obj1, obj2) {
1144 return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;
1145 };
1146 goog.array.sort(arr, stableCompareFn);
1147 for (var i = 0; i < arr.length; i++) {
1148 arr[i] = arr[i].value;
1149 }
1150};
1151
1152
1153/**
1154 * Sorts an array of objects by the specified object key and compare
1155 * function. If no compare function is provided, the key values are
1156 * compared in ascending order using <code>goog.array.defaultCompare</code>.
1157 * This won't work for keys that get renamed by the compiler. So use
1158 * {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.
1159 * @param {Array.<Object>} arr An array of objects to sort.
1160 * @param {string} key The object key to sort by.
1161 * @param {Function=} opt_compareFn The function to use to compare key
1162 * values.
1163 */
1164goog.array.sortObjectsByKey = function(arr, key, opt_compareFn) {
1165 var compare = opt_compareFn || goog.array.defaultCompare;
1166 goog.array.sort(arr, function(a, b) {
1167 return compare(a[key], b[key]);
1168 });
1169};
1170
1171
1172/**
1173 * Tells if the array is sorted.
1174 * @param {!Array.<T>} arr The array.
1175 * @param {?function(T,T):number=} opt_compareFn Function to compare the
1176 * array elements.
1177 * Should take 2 arguments to compare, and return a negative number, zero,
1178 * or a positive number depending on whether the first argument is less
1179 * than, equal to, or greater than the second.
1180 * @param {boolean=} opt_strict If true no equal elements are allowed.
1181 * @return {boolean} Whether the array is sorted.
1182 * @template T
1183 */
1184goog.array.isSorted = function(arr, opt_compareFn, opt_strict) {
1185 var compare = opt_compareFn || goog.array.defaultCompare;
1186 for (var i = 1; i < arr.length; i++) {
1187 var compareResult = compare(arr[i - 1], arr[i]);
1188 if (compareResult > 0 || compareResult == 0 && opt_strict) {
1189 return false;
1190 }
1191 }
1192 return true;
1193};
1194
1195
1196/**
1197 * Compares two arrays for equality. Two arrays are considered equal if they
1198 * have the same length and their corresponding elements are equal according to
1199 * the comparison function.
1200 *
1201 * @param {goog.array.ArrayLike} arr1 The first array to compare.
1202 * @param {goog.array.ArrayLike} arr2 The second array to compare.
1203 * @param {Function=} opt_equalsFn Optional comparison function.
1204 * Should take 2 arguments to compare, and return true if the arguments
1205 * are equal. Defaults to {@link goog.array.defaultCompareEquality} which
1206 * compares the elements using the built-in '===' operator.
1207 * @return {boolean} Whether the two arrays are equal.
1208 */
1209goog.array.equals = function(arr1, arr2, opt_equalsFn) {
1210 if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||
1211 arr1.length != arr2.length) {
1212 return false;
1213 }
1214 var l = arr1.length;
1215 var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality;
1216 for (var i = 0; i < l; i++) {
1217 if (!equalsFn(arr1[i], arr2[i])) {
1218 return false;
1219 }
1220 }
1221 return true;
1222};
1223
1224
1225/**
1226 * 3-way array compare function.
1227 * @param {!Array.<VALUE>|!goog.array.ArrayLike} arr1 The first array to
1228 * compare.
1229 * @param {!Array.<VALUE>|!goog.array.ArrayLike} arr2 The second array to
1230 * compare.
1231 * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
1232 * function by which the array is to be ordered. Should take 2 arguments to
1233 * compare, and return a negative number, zero, or a positive number
1234 * depending on whether the first argument is less than, equal to, or
1235 * greater than the second.
1236 * @return {number} Negative number, zero, or a positive number depending on
1237 * whether the first argument is less than, equal to, or greater than the
1238 * second.
1239 * @template VALUE
1240 */
1241goog.array.compare3 = function(arr1, arr2, opt_compareFn) {
1242 var compare = opt_compareFn || goog.array.defaultCompare;
1243 var l = Math.min(arr1.length, arr2.length);
1244 for (var i = 0; i < l; i++) {
1245 var result = compare(arr1[i], arr2[i]);
1246 if (result != 0) {
1247 return result;
1248 }
1249 }
1250 return goog.array.defaultCompare(arr1.length, arr2.length);
1251};
1252
1253
1254/**
1255 * Compares its two arguments for order, using the built in < and >
1256 * operators.
1257 * @param {VALUE} a The first object to be compared.
1258 * @param {VALUE} b The second object to be compared.
1259 * @return {number} A negative number, zero, or a positive number as the first
1260 * argument is less than, equal to, or greater than the second.
1261 * @template VALUE
1262 */
1263goog.array.defaultCompare = function(a, b) {
1264 return a > b ? 1 : a < b ? -1 : 0;
1265};
1266
1267
1268/**
1269 * Compares its two arguments for equality, using the built in === operator.
1270 * @param {*} a The first object to compare.
1271 * @param {*} b The second object to compare.
1272 * @return {boolean} True if the two arguments are equal, false otherwise.
1273 */
1274goog.array.defaultCompareEquality = function(a, b) {
1275 return a === b;
1276};
1277
1278
1279/**
1280 * Inserts a value into a sorted array. The array is not modified if the
1281 * value is already present.
1282 * @param {Array.<VALUE>|goog.array.ArrayLike} array The array to modify.
1283 * @param {VALUE} value The object to insert.
1284 * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
1285 * function by which the array is ordered. Should take 2 arguments to
1286 * compare, and return a negative number, zero, or a positive number
1287 * depending on whether the first argument is less than, equal to, or
1288 * greater than the second.
1289 * @return {boolean} True if an element was inserted.
1290 * @template VALUE
1291 */
1292goog.array.binaryInsert = function(array, value, opt_compareFn) {
1293 var index = goog.array.binarySearch(array, value, opt_compareFn);
1294 if (index < 0) {
1295 goog.array.insertAt(array, value, -(index + 1));
1296 return true;
1297 }
1298 return false;
1299};
1300
1301
1302/**
1303 * Removes a value from a sorted array.
1304 * @param {!Array.<VALUE>|!goog.array.ArrayLike} array The array to modify.
1305 * @param {VALUE} value The object to remove.
1306 * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
1307 * function by which the array is ordered. Should take 2 arguments to
1308 * compare, and return a negative number, zero, or a positive number
1309 * depending on whether the first argument is less than, equal to, or
1310 * greater than the second.
1311 * @return {boolean} True if an element was removed.
1312 * @template VALUE
1313 */
1314goog.array.binaryRemove = function(array, value, opt_compareFn) {
1315 var index = goog.array.binarySearch(array, value, opt_compareFn);
1316 return (index >= 0) ? goog.array.removeAt(array, index) : false;
1317};
1318
1319
1320/**
1321 * Splits an array into disjoint buckets according to a splitting function.
1322 * @param {Array.<T>} array The array.
1323 * @param {function(this:S, T,number,Array.<T>):?} sorter Function to call for
1324 * every element. This takes 3 arguments (the element, the index and the
1325 * array) and must return a valid object key (a string, number, etc), or
1326 * undefined, if that object should not be placed in a bucket.
1327 * @param {S=} opt_obj The object to be used as the value of 'this' within
1328 * sorter.
1329 * @return {!Object} An object, with keys being all of the unique return values
1330 * of sorter, and values being arrays containing the items for
1331 * which the splitter returned that key.
1332 * @template T,S
1333 */
1334goog.array.bucket = function(array, sorter, opt_obj) {
1335 var buckets = {};
1336
1337 for (var i = 0; i < array.length; i++) {
1338 var value = array[i];
1339 var key = sorter.call(opt_obj, value, i, array);
1340 if (goog.isDef(key)) {
1341 // Push the value to the right bucket, creating it if necessary.
1342 var bucket = buckets[key] || (buckets[key] = []);
1343 bucket.push(value);
1344 }
1345 }
1346
1347 return buckets;
1348};
1349
1350
1351/**
1352 * Creates a new object built from the provided array and the key-generation
1353 * function.
1354 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array like object over
1355 * which to iterate whose elements will be the values in the new object.
1356 * @param {?function(this:S, T, number, ?) : string} keyFunc The function to
1357 * call for every element. This function takes 3 arguments (the element, the
1358 * index and the array) and should return a string that will be used as the
1359 * key for the element in the new object. If the function returns the same
1360 * key for more than one element, the value for that key is
1361 * implementation-defined.
1362 * @param {S=} opt_obj The object to be used as the value of 'this'
1363 * within keyFunc.
1364 * @return {!Object.<T>} The new object.
1365 * @template T,S
1366 */
1367goog.array.toObject = function(arr, keyFunc, opt_obj) {
1368 var ret = {};
1369 goog.array.forEach(arr, function(element, index) {
1370 ret[keyFunc.call(opt_obj, element, index, arr)] = element;
1371 });
1372 return ret;
1373};
1374
1375
1376/**
1377 * Creates a range of numbers in an arithmetic progression.
1378 *
1379 * Range takes 1, 2, or 3 arguments:
1380 * <pre>
1381 * range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]
1382 * range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]
1383 * range(-2, -5, -1) produces [-2, -3, -4]
1384 * range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.
1385 * </pre>
1386 *
1387 * @param {number} startOrEnd The starting value of the range if an end argument
1388 * is provided. Otherwise, the start value is 0, and this is the end value.
1389 * @param {number=} opt_end The optional end value of the range.
1390 * @param {number=} opt_step The step size between range values. Defaults to 1
1391 * if opt_step is undefined or 0.
1392 * @return {!Array.<number>} An array of numbers for the requested range. May be
1393 * an empty array if adding the step would not converge toward the end
1394 * value.
1395 */
1396goog.array.range = function(startOrEnd, opt_end, opt_step) {
1397 var array = [];
1398 var start = 0;
1399 var end = startOrEnd;
1400 var step = opt_step || 1;
1401 if (opt_end !== undefined) {
1402 start = startOrEnd;
1403 end = opt_end;
1404 }
1405
1406 if (step * (end - start) < 0) {
1407 // Sign mismatch: start + step will never reach the end value.
1408 return [];
1409 }
1410
1411 if (step > 0) {
1412 for (var i = start; i < end; i += step) {
1413 array.push(i);
1414 }
1415 } else {
1416 for (var i = start; i > end; i += step) {
1417 array.push(i);
1418 }
1419 }
1420 return array;
1421};
1422
1423
1424/**
1425 * Returns an array consisting of the given value repeated N times.
1426 *
1427 * @param {VALUE} value The value to repeat.
1428 * @param {number} n The repeat count.
1429 * @return {!Array.<VALUE>} An array with the repeated value.
1430 * @template VALUE
1431 */
1432goog.array.repeat = function(value, n) {
1433 var array = [];
1434 for (var i = 0; i < n; i++) {
1435 array[i] = value;
1436 }
1437 return array;
1438};
1439
1440
1441/**
1442 * Returns an array consisting of every argument with all arrays
1443 * expanded in-place recursively.
1444 *
1445 * @param {...*} var_args The values to flatten.
1446 * @return {!Array} An array containing the flattened values.
1447 */
1448goog.array.flatten = function(var_args) {
1449 var result = [];
1450 for (var i = 0; i < arguments.length; i++) {
1451 var element = arguments[i];
1452 if (goog.isArray(element)) {
1453 result.push.apply(result, goog.array.flatten.apply(null, element));
1454 } else {
1455 result.push(element);
1456 }
1457 }
1458 return result;
1459};
1460
1461
1462/**
1463 * Rotates an array in-place. After calling this method, the element at
1464 * index i will be the element previously at index (i - n) %
1465 * array.length, for all values of i between 0 and array.length - 1,
1466 * inclusive.
1467 *
1468 * For example, suppose list comprises [t, a, n, k, s]. After invoking
1469 * rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].
1470 *
1471 * @param {!Array.<T>} array The array to rotate.
1472 * @param {number} n The amount to rotate.
1473 * @return {!Array.<T>} The array.
1474 * @template T
1475 */
1476goog.array.rotate = function(array, n) {
1477 goog.asserts.assert(array.length != null);
1478
1479 if (array.length) {
1480 n %= array.length;
1481 if (n > 0) {
1482 goog.array.ARRAY_PROTOTYPE_.unshift.apply(array, array.splice(-n, n));
1483 } else if (n < 0) {
1484 goog.array.ARRAY_PROTOTYPE_.push.apply(array, array.splice(0, -n));
1485 }
1486 }
1487 return array;
1488};
1489
1490
1491/**
1492 * Moves one item of an array to a new position keeping the order of the rest
1493 * of the items. Example use case: keeping a list of JavaScript objects
1494 * synchronized with the corresponding list of DOM elements after one of the
1495 * elements has been dragged to a new position.
1496 * @param {!(Array|Arguments|{length:number})} arr The array to modify.
1497 * @param {number} fromIndex Index of the item to move between 0 and
1498 * {@code arr.length - 1}.
1499 * @param {number} toIndex Target index between 0 and {@code arr.length - 1}.
1500 */
1501goog.array.moveItem = function(arr, fromIndex, toIndex) {
1502 goog.asserts.assert(fromIndex >= 0 && fromIndex < arr.length);
1503 goog.asserts.assert(toIndex >= 0 && toIndex < arr.length);
1504 // Remove 1 item at fromIndex.
1505 var removedItems = goog.array.ARRAY_PROTOTYPE_.splice.call(arr, fromIndex, 1);
1506 // Insert the removed item at toIndex.
1507 goog.array.ARRAY_PROTOTYPE_.splice.call(arr, toIndex, 0, removedItems[0]);
1508 // We don't use goog.array.insertAt and goog.array.removeAt, because they're
1509 // significantly slower than splice.
1510};
1511
1512
1513/**
1514 * Creates a new array for which the element at position i is an array of the
1515 * ith element of the provided arrays. The returned array will only be as long
1516 * as the shortest array provided; additional values are ignored. For example,
1517 * the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].
1518 *
1519 * This is similar to the zip() function in Python. See {@link
1520 * http://docs.python.org/library/functions.html#zip}
1521 *
1522 * @param {...!goog.array.ArrayLike} var_args Arrays to be combined.
1523 * @return {!Array.<!Array>} A new array of arrays created from provided arrays.
1524 */
1525goog.array.zip = function(var_args) {
1526 if (!arguments.length) {
1527 return [];
1528 }
1529 var result = [];
1530 for (var i = 0; true; i++) {
1531 var value = [];
1532 for (var j = 0; j < arguments.length; j++) {
1533 var arr = arguments[j];
1534 // If i is larger than the array length, this is the shortest array.
1535 if (i >= arr.length) {
1536 return result;
1537 }
1538 value.push(arr[i]);
1539 }
1540 result.push(value);
1541 }
1542};
1543
1544
1545/**
1546 * Shuffles the values in the specified array using the Fisher-Yates in-place
1547 * shuffle (also known as the Knuth Shuffle). By default, calls Math.random()
1548 * and so resets the state of that random number generator. Similarly, may reset
1549 * the state of the any other specified random number generator.
1550 *
1551 * Runtime: O(n)
1552 *
1553 * @param {!Array} arr The array to be shuffled.
1554 * @param {function():number=} opt_randFn Optional random function to use for
1555 * shuffling.
1556 * Takes no arguments, and returns a random number on the interval [0, 1).
1557 * Defaults to Math.random() using JavaScript's built-in Math library.
1558 */
1559goog.array.shuffle = function(arr, opt_randFn) {
1560 var randFn = opt_randFn || Math.random;
1561
1562 for (var i = arr.length - 1; i > 0; i--) {
1563 // Choose a random array index in [0, i] (inclusive with i).
1564 var j = Math.floor(randFn() * (i + 1));
1565
1566 var tmp = arr[i];
1567 arr[i] = arr[j];
1568 arr[j] = tmp;
1569 }
1570};