# 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 at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// 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 and13// limitations under the License.1415/**16 * @fileoverview Utilities for manipulating arrays.17 *18 */192021goog.provide('goog.array');22goog.provide('goog.array.ArrayLike');2324goog.require('goog.asserts');252627/**28 * @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should29 * rely on Array.prototype functions, if available.30 *31 * The Array.prototype functions can be defined by external libraries like32 * Prototype and setting this flag to false forces closure to use its own33 * goog.array implementation.34 *35 * If your javascript can be loaded by a third party site and you are wary about36 * relying on the prototype functions, specify37 * "--define goog.NATIVE_ARRAY_PROTOTYPES=false" to the JSCompiler.38 *39 * Setting goog.TRUSTED_SITE to false will automatically set40 * NATIVE_ARRAY_PROTOTYPES to false.41 */42goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE);434445/**46 * @define {boolean} If true, JSCompiler will use the native implementation of47 * array functions where appropriate (e.g., {@code Array#filter}) and remove the48 * unused pure JS implementation.49 */50goog.define('goog.array.ASSUME_NATIVE_FUNCTIONS', false);515253/**54 * @typedef {Array|NodeList|Arguments|{length: number}}55 */56goog.array.ArrayLike;575859/**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 T65 */66goog.array.peek = function(array) {67  return array[array.length - 1];68};697071/**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 T77 */78goog.array.last = goog.array.peek;798081/**82 * Reference to the original {@code Array.prototype}.83 * @private84 */85goog.array.ARRAY_PROTOTYPE_ = Array.prototype;868788// NOTE(arv): Since most of the array functions are generic it allows you to89// 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 just91// use the array path even if the browser supports indexing into strings. We92// therefore end up splitting the string.939495/**96 * Returns the index of the first element of an array with a specified value, or97 * -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. If104 *     omitted the search starts at index 0.105 * @return {number} The index of the first matching array element.106 * @template T107 */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);113114      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);120121      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      }128129      for (var i = fromIndex; i < arr.length; i++) {130        if (i in arr && arr[i] === obj)131          return i;132      }133      return -1;134    };135136137/**138 * Returns the index of the last element of an array with a specified value, or139 * -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. If146 *     omitted the search starts at the end of the array.147 * @return {number} The index of the last matching array element.148 * @template T149 */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);155156      // Firefox treats undefined and null as 0 in the fromIndex argument which157      // leads it to always return -1158      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;163164      if (fromIndex < 0) {165        fromIndex = Math.max(0, arr.length + fromIndex);166      }167168      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      }175176      for (var i = fromIndex; i >= 0; i--) {177        if (i in arr && arr[i] === obj)178          return i;179      }180      return -1;181    };182183184/**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 over189 *     which to iterate.190 * @param {?function(this: S, T, number, ?): ?} f The function to call for every191 *     element. This function takes 3 arguments (the element, the index and the192 *     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,S195 */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);201202      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 docs206      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    };213214215/**216 * Calls a function for each element in an array, starting from the last217 * element rather than the first.218 *219 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array220 *     like object over which to iterate.221 * @param {?function(this: S, T, number, ?): ?} f The function to call for every222 *     element. This function223 *     takes 3 arguments (the element, the index and the array). The return224 *     value is ignored.225 * @param {S=} opt_obj The object to be used as the value of 'this'226 *     within f.227 * @template T,S228 */229goog.array.forEachRight = function(arr, f, opt_obj) {230  var l = arr.length;  // must be fixed during loop... see docs231  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};238239240/**241 * Calls a function for each element in an array, and if the function returns242 * 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 array247 *     like object over which to iterate.248 * @param {?function(this:S, T, number, ?):boolean} f The function to call for249 *     every element. This function250 *     takes 3 arguments (the element, the index and the array) and must251 *     return a Boolean. If the return value is true the element is added to the252 *     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 test256 *     are present.257 * @template T,S258 */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);264265      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 docs269      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 arr2275          if (f.call(opt_obj, val, i, arr)) {276            res[resLength++] = val;277          }278        }279      }280      return res;281    };282283284/**285 * Calls a function for each element in an array and inserts the result into a286 * 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 object291 *     over which to iterate.292 * @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call293 *     for every element. This function takes 3 arguments (the element,294 *     the index and the array) and should return something. The result will be295 *     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, RESULT299 */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);305306      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 docs310      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    };319320321/**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 10330 *331 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array332 *     like object over which to iterate.333 * @param {?function(this:S, R, T, number, ?) : R} f The function to call for334 *     every element. This function335 *     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 the337 *     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,R344 */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    };362363364/**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 array376 *     like object over which to iterate.377 * @param {?function(this:S, R, T, number, ?) : R} f The function to call for378 *     every element. This function379 *     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 the381 *     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 the387 *     values of the array.388 * @template T,S,R389 */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    };407408409/**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 calls412 * 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 array417 *     like object over which to iterate.418 * @param {?function(this:S, T, number, ?) : boolean} f The function to call for419 *     for every element. This function takes 3 arguments (the element, the420 *     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,S425 */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);431432      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 docs436      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    };444445446/**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 and449 * 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 array454 *     like object over which to iterate.455 * @param {?function(this:S, T, number, ?) : boolean} f The function to call for456 *     for every element. This function takes 3 arguments (the element, the457 *     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,S462 */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);468469      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 docs473      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    };481482483/**484 * Counts the array elements that fulfill the predicate, i.e. for which the485 * callback function returns true. Skips holes in the array.486 *487 * @param {!(Array.<T>|goog.array.ArrayLike)} arr Array or array like object488 *     over which to iterate.489 * @param {function(this: S, T, number, ?): boolean} f The function to call for490 *     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,S494 */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};504505506/**507 * Search an array for the first element that satisfies a given condition and508 * return that element.509 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array510 *     like object over which to iterate.511 * @param {?function(this:S, T, number, ?) : boolean} f The function to call512 *     for every element. This function takes 3 arguments (the element, the513 *     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 no516 *     element is found.517 * @template T,S518 */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};523524525/**526 * Search an array for the first element that satisfies a given condition and527 * return its index.528 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array529 *     like object over which to iterate.530 * @param {?function(this:S, T, number, ?) : boolean} f The function to call for531 *     every element. This function532 *     takes 3 arguments (the element, the index and the array) and should533 *     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,S538 */539goog.array.findIndex = function(arr, f, opt_obj) {540  var l = arr.length;  // must be fixed during loop... see docs541  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};549550551/**552 * Search an array (in reverse order) for the last element that satisfies a553 * given condition and return that element.554 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array555 *     like object over which to iterate.556 * @param {?function(this:S, T, number, ?) : boolean} f The function to call557 *     for every element. This function558 *     takes 3 arguments (the element, the index and the array) and should559 *     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 no562 *     element is found.563 * @template T,S564 */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};569570571/**572 * Search an array (in reverse order) for the last element that satisfies a573 * given condition and return its index.574 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array575 *     like object over which to iterate.576 * @param {?function(this:S, T, number, ?) : boolean} f The function to call577 *     for every element. This function578 *     takes 3 arguments (the element, the index and the array) and should579 *     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,S584 */585goog.array.findIndexRight = function(arr, f, opt_obj) {586  var l = arr.length;  // must be fixed during loop... see docs587  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};595596597/**598 * Whether the array contains the given object.599 * @param {goog.array.ArrayLike} arr The array to test for the presence of the600 *     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};607608609/**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};617618619/**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 the625  // 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};633634635/**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 T640 */641goog.array.insert = function(arr, obj) {642  if (!goog.array.contains(arr, obj)) {643    arr.push(obj);644  }645};646647648/**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};658659660/**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};670671672/**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 obj2677 *     is omitted or not found, obj is inserted at the end of the array.678 * @template T679 */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};688689690/**691 * Removes the first occurrence of a particular value from an array.692 * @param {Array.<T>|goog.array.ArrayLike} arr Array from which to remove693 *     value.694 * @param {T} obj Object to remove.695 * @return {boolean} True if an element was removed.696 * @template T697 */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};706707708/**709 * Removes from an array the element at index i710 * @param {goog.array.ArrayLike} arr Array or array like object from which to711 *     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);717718  // use generic form of splice719  // splice returns the removed items and if successful the length of that720  // will be 1721  return goog.array.ARRAY_PROTOTYPE_.splice.call(arr, i, 1).length == 1;722};723724725/**726 * Removes the first value that satisfies the given condition.727 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array728 *     like object over which to iterate.729 * @param {?function(this:S, T, number, ?) : boolean} f The function to call730 *     for every element. This function731 *     takes 3 arguments (the element, the index and the array) and should732 *     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,S736 */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};745746747/**748 * Removes all values that satisfy the given condition.749 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array750 *     like object over which to iterate.751 * @param {?function(this:S, T, number, ?) : boolean} f The function to call752 *     for every element. This function753 *     takes 3 arguments (the element, the index and the array) and should754 *     return a boolean.755 * @param {S=} opt_obj An optional "this" context for the function.756 * @return {number} The number of items removed757 * @template T,S758 */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};770771772/**773 * Returns a new array that is the result of joining the arguments.  If arrays774 * are passed then their items are added, however, if non-arrays are passed they775 * will be added to the return array as is.776 *777 * Note that ArrayLike objects will be added as is, rather than having their778 * 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 created785 * in an iframe become corrupted soon (not immediately) after the iframe is786 * destroyed. This is common if loading data via goog.net.IframeIo, for example.787 * This corruption only affects the concat method which will start throwing788 * 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 to793 * work on these broken array objects.794 *795 * @param {...*} var_args Items to concatenate.  Arrays will have each item796 *     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};803804805/**806 * Returns a new array that contains the contents of all the arrays passed.807 * @param {...!Array.<T>} var_args808 * @return {!Array.<T>}809 * @template T810 */811goog.array.join = function(var_args) {812  return goog.array.ARRAY_PROTOTYPE_.concat.apply(813      goog.array.ARRAY_PROTOTYPE_, arguments);814};815816817/**818 * Converts an object to an array.819 * @param {Array.<T>|goog.array.ArrayLike} object  The object to convert to an820 *     array.821 * @return {!Array.<T>} The object converted into an array. If object has a822 *     length property, every property indexed with a non-negative number823 *     less than length will be included in the result. If object does not824 *     have a length property, an empty array will be returned.825 * @template T826 */827goog.array.toArray = function(object) {828  var length = object.length;829830  // If length is not a number the following it false. This case is kept for831  // backwards compatibility since there are callers that pass objects that are832  // 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};842843844/**845 * Does a shallow copy of an array.846 * @param {Array.<T>|goog.array.ArrayLike} arr  Array or array-like object to847 *     clone.848 * @return {!Array.<T>} Clone of the input array.849 * @template T850 */851goog.array.clone = goog.array.toArray;852853854/**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 elements867 *     to add to arr1.868 * @template VALUE869 */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 push874    // directly.875    var isArrayLike;876    if (goog.isArray(arr2) ||877        // Detect Arguments. ES5 says that the [[Class]] of an Arguments object878        // is "Arguments" but only V8 and JSC/Safari gets this right. We instead879        // 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 mode882            // 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};897898899/**900 * Adds or removes elements from an array. This is a generic version of Array901 * 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 the906 *     array. If not defined, treated as 0.907 * @param {number} howMany How many elements to remove (0 means no removal. A908 *     value below 0 is treated as zero and so is any other non number. Numbers909 *     are floored).910 * @param {...T} var_args Optional, additional elements to insert into the911 *     array.912 * @return {!Array.<T>} the removed elements.913 * @template T914 */915goog.array.splice = function(arr, index, howMany, var_args) {916  goog.asserts.assert(arr.length != null);917918  return goog.array.ARRAY_PROTOTYPE_.splice.apply(919      arr, goog.array.slice(arguments, 1));920};921922923/**924 * Returns a new array from a segment of an array. This is a generic version of925 * Array slice. This means that it might work on other objects similar to926 * arrays, such as the arguments object.927 *928 * @param {Array.<T>|goog.array.ArrayLike} arr The array from929 * 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 the933 *     original array.934 * @template T935 */936goog.array.slice = function(arr, start, opt_end) {937  goog.asserts.assert(arr.length != null);938939  // passing 1 arg to slice is not the same as passing 2 where the second is940  // 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 of942  // testing the length943  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};949950951/**952 * Removes all duplicates from an array (retaining only the first953 * occurrence of each array element).  This function modifies the954 * 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 as957 * defined by {@link goog.getUid}.958 *959 * Alternatively you can specify a custom hash function that returns a unique960 * 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 remove966 *     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 original969 *     array will remain unchanged.970 * @param {function(T):string=} opt_hashFn An optional function to use to971 *     apply to every item in the array. This function should return a unique972 *     value for each item in the array it should consider unique.973 * @template T974 */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 to979    // 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;984985  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};996997998/**999 * Searches the specified array for the specified target using the binary1000 * search algorithm.  If no opt_compareFn is specified, elements are compared1001 * using <code>goog.array.defaultCompare</code>, which compares the elements1002 * using the built in < and > operators.  This will produce the expected1003 * behavior for homogeneous arrays of String(s) and Number(s). The array1004 * specified <b>must</b> be sorted in ascending order (as defined by the1005 * comparison function).  If the array is not sorted, results are undefined.1006 * If the array contains multiple instances of the specified target value, any1007 * 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 comparison1014 *     function by which the array is ordered. Should take 2 arguments to1015 *     compare, and return a negative number, zero, or a positive number1016 *     depending on whether the first argument is less than, equal to, or1017 *     greater than the second.1018 * @return {number} Lowest index of the target value if found, otherwise1019 *     (-(insertion point) - 1). The insertion point is where the value should1020 *     be inserted into arr to preserve the sorted property.  Return value >= 01021 *     iff target is found.1022 * @template TARGET, VALUE1023 */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};102910301031/**1032 * Selects an index in the specified array using the binary search algorithm.1033 * The evaluator receives an element and determines whether the desired index1034 * 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} evaluator1042 *     Evaluator function that receives 3 arguments (the element, the index and1043 *     the array). Should return a negative number, zero, or a positive number1044 *     depending on whether the desired index is before, at, or after the1045 *     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, if1049 *     such exists; otherwise (-(insertion point) - 1). The insertion point is1050 *     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-negative1052 *     iff a match is found.1053 * @template THIS, VALUE1054 */1055goog.array.binarySelect = function(arr, evaluator, opt_obj) {1056  return goog.array.binarySearch_(arr, evaluator, true /* isEvaluator */,1057      undefined /* opt_target */, opt_obj);1058};105910601061/**1062 * Implementation of a binary search algorithm which knows how to use both1063 * comparison functions and evaluators. If an evaluator is provided, will call1064 * the evaluator with the given optional data object, conforming to the1065 * interface defined in binarySelect. Otherwise, if a comparison function is1066 * provided, will call the comparison function against the given data object.1067 *1068 * This implementation purposefully does not use goog.bind or goog.partial for1069 * 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 an1076 *     evaluator or a comparison function, as defined by binarySearch1077 *     and binarySelect above.1078 * @param {boolean} isEvaluator Whether the function is an evaluator or a1079 *     comparison function.1080 * @param {TARGET=} opt_target If the function is a comparison function, then1081 *     this is the target to binary search for.1082 * @param {THIS=} opt_selfObj If the function is an evaluator, this is an1083  *    optional this object for the evaluator.1084 * @return {number} Lowest index of the target value if found, otherwise1085 *     (-(insertion point) - 1). The insertion point is where the value should1086 *     be inserted into arr to preserve the sorted property.  Return value >= 01087 *     iff target is found.1088 * @template THIS, VALUE, TARGET1089 * @private1090 */1091goog.array.binarySearch_ = function(arr, compareFn, isEvaluator, opt_target,1092    opt_selfObj) {1093  var left = 0;  // inclusive1094  var right = arr.length;  // exclusive1095  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};111611171118/**1119 * Sorts the specified array into ascending order.  If no opt_compareFn is1120 * specified, elements are compared using1121 * <code>goog.array.defaultCompare</code>, which compares the elements using1122 * the built in < and > operators.  This will produce the expected behavior1123 * for homogeneous arrays of String(s) and Number(s), unlike the native sort,1124 * but will give unpredictable results for heterogenous lists of strings and1125 * 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 comparison1133 *     function by which the1134 *     array is to be ordered. Should take 2 arguments to compare, and return a1135 *     negative number, zero, or a positive number depending on whether the1136 *     first argument is less than, equal to, or greater than the second.1137 * @template T1138 */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};114311441145/**1146 * Sorts the specified array into ascending order in a stable way.  If no1147 * opt_compareFn is specified, elements are compared using1148 * <code>goog.array.defaultCompare</code>, which compares the elements using1149 * the built in < and > operators.  This will produce the expected behavior1150 * for homogeneous arrays of String(s) and Number(s).1151 *1152 * Runtime: Same as <code>Array.prototype.sort</code>, plus an additional1153 * 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 function1157 *     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 on1159 *     whether the first argument is less than, equal to, or greater than the1160 *     second.1161 * @template T1162 */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};117611771178/**1179 * Sorts an array of objects by the specified object key and compare1180 * function. If no compare function is provided, the key values are1181 * compared in ascending order using <code>goog.array.defaultCompare</code>.1182 * This won't work for keys that get renamed by the compiler. So use1183 * {'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 key1187 *     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};119511961197/**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 the1201 *     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 less1204 *     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 T1208 */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};121912201221/**1222 * Compares two arrays for equality. Two arrays are considered equal if they1223 * have the same length and their corresponding elements are equal according to1224 * 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 arguments1230 *     are equal. Defaults to {@link goog.array.defaultCompareEquality} which1231 *     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};124812491250/**1251 * 3-way array compare function.1252 * @param {!Array.<VALUE>|!goog.array.ArrayLike} arr1 The first array to1253 *     compare.1254 * @param {!Array.<VALUE>|!goog.array.ArrayLike} arr2 The second array to1255 *     compare.1256 * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison1257 *     function by which the array is to be ordered. Should take 2 arguments to1258 *     compare, and return a negative number, zero, or a positive number1259 *     depending on whether the first argument is less than, equal to, or1260 *     greater than the second.1261 * @return {number} Negative number, zero, or a positive number depending on1262 *     whether the first argument is less than, equal to, or greater than the1263 *     second.1264 * @template VALUE1265 */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};127712781279/**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 first1285 *     argument is less than, equal to, or greater than the second.1286 * @template VALUE1287 */1288goog.array.defaultCompare = function(a, b) {1289  return a > b ? 1 : a < b ? -1 : 0;1290};129112921293/**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};130213031304/**1305 * Inserts a value into a sorted array. The array is not modified if the1306 * 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 comparison1310 *     function by which the array is ordered. Should take 2 arguments to1311 *     compare, and return a negative number, zero, or a positive number1312 *     depending on whether the first argument is less than, equal to, or1313 *     greater than the second.1314 * @return {boolean} True if an element was inserted.1315 * @template VALUE1316 */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};132513261327/**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 comparison1332 *     function by which the array is ordered. Should take 2 arguments to1333 *     compare, and return a negative number, zero, or a positive number1334 *     depending on whether the first argument is less than, equal to, or1335 *     greater than the second.1336 * @return {boolean} True if an element was removed.1337 * @template VALUE1338 */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};134313441345/**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 for1349 *     every element.  This takes 3 arguments (the element, the index and the1350 *     array) and must return a valid object key (a string, number, etc), or1351 *     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' within1353 *     sorter.1354 * @return {!Object} An object, with keys being all of the unique return values1355 *     of sorter, and values being arrays containing the items for1356 *     which the splitter returned that key.1357 * @template T,S1358 */1359goog.array.bucket = function(array, sorter, opt_obj) {1360  var buckets = {};13611362  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  }13711372  return buckets;1373};137413751376/**1377 * Creates a new object built from the provided array and the key-generation1378 * function.1379 * @param {Array.<T>|goog.array.ArrayLike} arr Array or array like object over1380 *     which to iterate whose elements will be the values in the new object.1381 * @param {?function(this:S, T, number, ?) : string} keyFunc The function to1382 *     call for every element. This function takes 3 arguments (the element, the1383 *     index and the array) and should return a string that will be used as the1384 *     key for the element in the new object. If the function returns the same1385 *     key for more than one element, the value for that key is1386 *     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,S1391 */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};139914001401/**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 argument1413 *     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 11416 *     if opt_step is undefined or 0.1417 * @return {!Array.<number>} An array of numbers for the requested range. May be1418 *     an empty array if adding the step would not converge toward the end1419 *     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  }14301431  if (step * (end - start) < 0) {1432    // Sign mismatch: start + step will never reach the end value.1433    return [];1434  }14351436  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};144714481449/**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 VALUE1456 */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};146414651466/**1467 * Returns an array consisting of every argument with all arrays1468 * 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};148514861487/**1488 * Rotates an array in-place. After calling this method, the element at1489 * 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 invoking1494 * 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 T1500 */1501goog.array.rotate = function(array, n) {1502  goog.asserts.assert(array.length != null);15031504  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};151415151516/**1517 * Moves one item of an array to a new position keeping the order of the rest1518 * of the items. Example use case: keeping a list of JavaScript objects1519 * synchronized with the corresponding list of DOM elements after one of the1520 * 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 and1523 *     {@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're1534  // significantly slower than splice.1535};153615371538/**1539 * Creates a new array for which the element at position i is an array of the1540 * ith element of the provided arrays.  The returned array will only be as long1541 * 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 {@link1545 * 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};156815691570/**1571 * Shuffles the values in the specified array using the Fisher-Yates in-place1572 * 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 reset1574 * 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 for1580 *     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;15861587  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));15901591    var tmp = arr[i];1592    arr[i] = arr[j];1593    arr[j] = tmp;1594  }1595};