Path: blob/trunk/third_party/closure/goog/array/array.js
2868 views
// Copyright 2006 The Closure Library Authors. All Rights Reserved.1//2// Licensed under the Apache License, Version 2.0 (the "License");3// you may not use this file except in compliance with the License.4// You may obtain a copy of the License at5//6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS-IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314/**15* @fileoverview Utilities for manipulating arrays.16*17* @author [email protected] (Erik Arvidsson)18*/192021goog.provide('goog.array');2223goog.require('goog.asserts');242526/**27* @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should28* rely on Array.prototype functions, if available.29*30* The Array.prototype functions can be defined by external libraries like31* Prototype and setting this flag to false forces closure to use its own32* goog.array implementation.33*34* If your javascript can be loaded by a third party site and you are wary about35* relying on the prototype functions, specify36* "--define goog.NATIVE_ARRAY_PROTOTYPES=false" to the JSCompiler.37*38* Setting goog.TRUSTED_SITE to false will automatically set39* NATIVE_ARRAY_PROTOTYPES to false.40*/41goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE);424344/**45* @define {boolean} If true, JSCompiler will use the native implementation of46* array functions where appropriate (e.g., {@code Array#filter}) and remove the47* unused pure JS implementation.48*/49goog.define('goog.array.ASSUME_NATIVE_FUNCTIONS', false);505152/**53* Returns the last element in an array without removing it.54* Same as goog.array.last.55* @param {IArrayLike<T>|string} array The array.56* @return {T} Last item in array.57* @template T58*/59goog.array.peek = function(array) {60return array[array.length - 1];61};626364/**65* Returns the last element in an array without removing it.66* Same as goog.array.peek.67* @param {IArrayLike<T>|string} array The array.68* @return {T} Last item in array.69* @template T70*/71goog.array.last = goog.array.peek;7273// NOTE(arv): Since most of the array functions are generic it allows you to74// pass an array-like object. Strings have a length and are considered array-75// like. However, the 'in' operator does not work on strings so we cannot just76// use the array path even if the browser supports indexing into strings. We77// therefore end up splitting the string.787980/**81* Returns the index of the first element of an array with a specified value, or82* -1 if the element is not present in the array.83*84* See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}85*86* @param {IArrayLike<T>|string} arr The array to be searched.87* @param {T} obj The object for which we are searching.88* @param {number=} opt_fromIndex The index at which to start the search. If89* omitted the search starts at index 0.90* @return {number} The index of the first matching array element.91* @template T92*/93goog.array.indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&94(goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.indexOf) ?95function(arr, obj, opt_fromIndex) {96goog.asserts.assert(arr.length != null);9798return Array.prototype.indexOf.call(arr, obj, opt_fromIndex);99} :100function(arr, obj, opt_fromIndex) {101var fromIndex = opt_fromIndex == null ?1020 :103(opt_fromIndex < 0 ? Math.max(0, arr.length + opt_fromIndex) :104opt_fromIndex);105106if (goog.isString(arr)) {107// Array.prototype.indexOf uses === so only strings should be found.108if (!goog.isString(obj) || obj.length != 1) {109return -1;110}111return arr.indexOf(obj, fromIndex);112}113114for (var i = fromIndex; i < arr.length; i++) {115if (i in arr && arr[i] === obj) return i;116}117return -1;118};119120121/**122* Returns the index of the last element of an array with a specified value, or123* -1 if the element is not present in the array.124*125* See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof}126*127* @param {!IArrayLike<T>|string} arr The array to be searched.128* @param {T} obj The object for which we are searching.129* @param {?number=} opt_fromIndex The index at which to start the search. If130* omitted the search starts at the end of the array.131* @return {number} The index of the last matching array element.132* @template T133*/134goog.array.lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&135(goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.lastIndexOf) ?136function(arr, obj, opt_fromIndex) {137goog.asserts.assert(arr.length != null);138139// Firefox treats undefined and null as 0 in the fromIndex argument which140// leads it to always return -1141var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;142return Array.prototype.lastIndexOf.call(arr, obj, fromIndex);143} :144function(arr, obj, opt_fromIndex) {145var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;146147if (fromIndex < 0) {148fromIndex = Math.max(0, arr.length + fromIndex);149}150151if (goog.isString(arr)) {152// Array.prototype.lastIndexOf uses === so only strings should be found.153if (!goog.isString(obj) || obj.length != 1) {154return -1;155}156return arr.lastIndexOf(obj, fromIndex);157}158159for (var i = fromIndex; i >= 0; i--) {160if (i in arr && arr[i] === obj) return i;161}162return -1;163};164165166/**167* Calls a function for each element in an array. Skips holes in the array.168* See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}169*170* @param {IArrayLike<T>|string} arr Array or array like object over171* which to iterate.172* @param {?function(this: S, T, number, ?): ?} f The function to call for every173* element. This function takes 3 arguments (the element, the index and the174* array). The return value is ignored.175* @param {S=} opt_obj The object to be used as the value of 'this' within f.176* @template T,S177*/178goog.array.forEach = goog.NATIVE_ARRAY_PROTOTYPES &&179(goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.forEach) ?180function(arr, f, opt_obj) {181goog.asserts.assert(arr.length != null);182183Array.prototype.forEach.call(arr, f, opt_obj);184} :185function(arr, f, opt_obj) {186var l = arr.length; // must be fixed during loop... see docs187var arr2 = goog.isString(arr) ? arr.split('') : arr;188for (var i = 0; i < l; i++) {189if (i in arr2) {190f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);191}192}193};194195196/**197* Calls a function for each element in an array, starting from the last198* element rather than the first.199*200* @param {IArrayLike<T>|string} arr Array or array201* like object over which to iterate.202* @param {?function(this: S, T, number, ?): ?} f The function to call for every203* element. This function204* takes 3 arguments (the element, the index and the array). The return205* value is ignored.206* @param {S=} opt_obj The object to be used as the value of 'this'207* within f.208* @template T,S209*/210goog.array.forEachRight = function(arr, f, opt_obj) {211var l = arr.length; // must be fixed during loop... see docs212var arr2 = goog.isString(arr) ? arr.split('') : arr;213for (var i = l - 1; i >= 0; --i) {214if (i in arr2) {215f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);216}217}218};219220221/**222* Calls a function for each element in an array, and if the function returns223* true adds the element to a new array.224*225* See {@link http://tinyurl.com/developer-mozilla-org-array-filter}226*227* @param {IArrayLike<T>|string} arr Array or array228* like object over which to iterate.229* @param {?function(this:S, T, number, ?):boolean} f The function to call for230* every element. This function231* takes 3 arguments (the element, the index and the array) and must232* return a Boolean. If the return value is true the element is added to the233* result array. If it is false the element is not included.234* @param {S=} opt_obj The object to be used as the value of 'this'235* within f.236* @return {!Array<T>} a new array in which only elements that passed the test237* are present.238* @template T,S239*/240goog.array.filter = goog.NATIVE_ARRAY_PROTOTYPES &&241(goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.filter) ?242function(arr, f, opt_obj) {243goog.asserts.assert(arr.length != null);244245return Array.prototype.filter.call(arr, f, opt_obj);246} :247function(arr, f, opt_obj) {248var l = arr.length; // must be fixed during loop... see docs249var res = [];250var resLength = 0;251var arr2 = goog.isString(arr) ? arr.split('') : arr;252for (var i = 0; i < l; i++) {253if (i in arr2) {254var val = arr2[i]; // in case f mutates arr2255if (f.call(/** @type {?} */ (opt_obj), val, i, arr)) {256res[resLength++] = val;257}258}259}260return res;261};262263264/**265* Calls a function for each element in an array and inserts the result into a266* new array.267*268* See {@link http://tinyurl.com/developer-mozilla-org-array-map}269*270* @param {IArrayLike<VALUE>|string} arr Array or array like object271* over which to iterate.272* @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call273* for every element. This function takes 3 arguments (the element,274* the index and the array) and should return something. The result will be275* inserted into a new array.276* @param {THIS=} opt_obj The object to be used as the value of 'this' within f.277* @return {!Array<RESULT>} a new array with the results from f.278* @template THIS, VALUE, RESULT279*/280goog.array.map = goog.NATIVE_ARRAY_PROTOTYPES &&281(goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.map) ?282function(arr, f, opt_obj) {283goog.asserts.assert(arr.length != null);284285return Array.prototype.map.call(arr, f, opt_obj);286} :287function(arr, f, opt_obj) {288var l = arr.length; // must be fixed during loop... see docs289var res = new Array(l);290var arr2 = goog.isString(arr) ? arr.split('') : arr;291for (var i = 0; i < l; i++) {292if (i in arr2) {293res[i] = f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);294}295}296return res;297};298299300/**301* Passes every element of an array into a function and accumulates the result.302*303* See {@link http://tinyurl.com/developer-mozilla-org-array-reduce}304*305* For example:306* var a = [1, 2, 3, 4];307* goog.array.reduce(a, function(r, v, i, arr) {return r + v;}, 0);308* returns 10309*310* @param {IArrayLike<T>|string} arr Array or array311* like object over which to iterate.312* @param {function(this:S, R, T, number, ?) : R} f The function to call for313* every element. This function314* takes 4 arguments (the function's previous result or the initial value,315* the value of the current array element, the current array index, and the316* array itself)317* function(previousValue, currentValue, index, array).318* @param {?} val The initial value to pass into the function on the first call.319* @param {S=} opt_obj The object to be used as the value of 'this'320* within f.321* @return {R} Result of evaluating f repeatedly across the values of the array.322* @template T,S,R323*/324goog.array.reduce = goog.NATIVE_ARRAY_PROTOTYPES &&325(goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduce) ?326function(arr, f, val, opt_obj) {327goog.asserts.assert(arr.length != null);328if (opt_obj) {329f = goog.bind(f, opt_obj);330}331return Array.prototype.reduce.call(arr, f, val);332} :333function(arr, f, val, opt_obj) {334var rval = val;335goog.array.forEach(arr, function(val, index) {336rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);337});338return rval;339};340341342/**343* Passes every element of an array into a function and accumulates the result,344* starting from the last element and working towards the first.345*346* See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright}347*348* For example:349* var a = ['a', 'b', 'c'];350* goog.array.reduceRight(a, function(r, v, i, arr) {return r + v;}, '');351* returns 'cba'352*353* @param {IArrayLike<T>|string} arr Array or array354* like object over which to iterate.355* @param {?function(this:S, R, T, number, ?) : R} f The function to call for356* every element. This function357* takes 4 arguments (the function's previous result or the initial value,358* the value of the current array element, the current array index, and the359* array itself)360* function(previousValue, currentValue, index, array).361* @param {?} val The initial value to pass into the function on the first call.362* @param {S=} opt_obj The object to be used as the value of 'this'363* within f.364* @return {R} Object returned as a result of evaluating f repeatedly across the365* values of the array.366* @template T,S,R367*/368goog.array.reduceRight = goog.NATIVE_ARRAY_PROTOTYPES &&369(goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduceRight) ?370function(arr, f, val, opt_obj) {371goog.asserts.assert(arr.length != null);372goog.asserts.assert(f != null);373if (opt_obj) {374f = goog.bind(f, opt_obj);375}376return Array.prototype.reduceRight.call(arr, f, val);377} :378function(arr, f, val, opt_obj) {379var rval = val;380goog.array.forEachRight(arr, function(val, index) {381rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);382});383return rval;384};385386387/**388* Calls f for each element of an array. If any call returns true, some()389* returns true (without checking the remaining elements). If all calls390* return false, some() returns false.391*392* See {@link http://tinyurl.com/developer-mozilla-org-array-some}393*394* @param {IArrayLike<T>|string} arr Array or array395* like object over which to iterate.396* @param {?function(this:S, T, number, ?) : boolean} f The function to call for397* for every element. This function takes 3 arguments (the element, the398* index and the array) and should return a boolean.399* @param {S=} opt_obj The object to be used as the value of 'this'400* within f.401* @return {boolean} true if any element passes the test.402* @template T,S403*/404goog.array.some = goog.NATIVE_ARRAY_PROTOTYPES &&405(goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.some) ?406function(arr, f, opt_obj) {407goog.asserts.assert(arr.length != null);408409return Array.prototype.some.call(arr, f, opt_obj);410} :411function(arr, f, opt_obj) {412var l = arr.length; // must be fixed during loop... see docs413var arr2 = goog.isString(arr) ? arr.split('') : arr;414for (var i = 0; i < l; i++) {415if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {416return true;417}418}419return false;420};421422423/**424* Call f for each element of an array. If all calls return true, every()425* returns true. If any call returns false, every() returns false and426* does not continue to check the remaining elements.427*428* See {@link http://tinyurl.com/developer-mozilla-org-array-every}429*430* @param {IArrayLike<T>|string} arr Array or array431* like object over which to iterate.432* @param {?function(this:S, T, number, ?) : boolean} f The function to call for433* for every element. This function takes 3 arguments (the element, the434* index and the array) and should return a boolean.435* @param {S=} opt_obj The object to be used as the value of 'this'436* within f.437* @return {boolean} false if any element fails the test.438* @template T,S439*/440goog.array.every = goog.NATIVE_ARRAY_PROTOTYPES &&441(goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.every) ?442function(arr, f, opt_obj) {443goog.asserts.assert(arr.length != null);444445return Array.prototype.every.call(arr, f, opt_obj);446} :447function(arr, f, opt_obj) {448var l = arr.length; // must be fixed during loop... see docs449var arr2 = goog.isString(arr) ? arr.split('') : arr;450for (var i = 0; i < l; i++) {451if (i in arr2 && !f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {452return false;453}454}455return true;456};457458459/**460* Counts the array elements that fulfill the predicate, i.e. for which the461* callback function returns true. Skips holes in the array.462*463* @param {!IArrayLike<T>|string} arr Array or array like object464* over which to iterate.465* @param {function(this: S, T, number, ?): boolean} f The function to call for466* every element. Takes 3 arguments (the element, the index and the array).467* @param {S=} opt_obj The object to be used as the value of 'this' within f.468* @return {number} The number of the matching elements.469* @template T,S470*/471goog.array.count = function(arr, f, opt_obj) {472var count = 0;473goog.array.forEach(arr, function(element, index, arr) {474if (f.call(/** @type {?} */ (opt_obj), element, index, arr)) {475++count;476}477}, opt_obj);478return count;479};480481482/**483* Search an array for the first element that satisfies a given condition and484* return that element.485* @param {IArrayLike<T>|string} arr Array or array486* like object over which to iterate.487* @param {?function(this:S, T, number, ?) : boolean} f The function to call488* for every element. This function takes 3 arguments (the element, the489* index and the array) and should return a boolean.490* @param {S=} opt_obj An optional "this" context for the function.491* @return {T|null} The first array element that passes the test, or null if no492* element is found.493* @template T,S494*/495goog.array.find = function(arr, f, opt_obj) {496var i = goog.array.findIndex(arr, f, opt_obj);497return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];498};499500501/**502* Search an array for the first element that satisfies a given condition and503* return its index.504* @param {IArrayLike<T>|string} arr Array or array505* like object over which to iterate.506* @param {?function(this:S, T, number, ?) : boolean} f The function to call for507* every element. This function508* takes 3 arguments (the element, the index and the array) and should509* return a boolean.510* @param {S=} opt_obj An optional "this" context for the function.511* @return {number} The index of the first array element that passes the test,512* or -1 if no element is found.513* @template T,S514*/515goog.array.findIndex = function(arr, f, opt_obj) {516var l = arr.length; // must be fixed during loop... see docs517var arr2 = goog.isString(arr) ? arr.split('') : arr;518for (var i = 0; i < l; i++) {519if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {520return i;521}522}523return -1;524};525526527/**528* Search an array (in reverse order) for the last element that satisfies a529* given condition and return that element.530* @param {IArrayLike<T>|string} arr Array or array531* like object over which to iterate.532* @param {?function(this:S, T, number, ?) : boolean} f The function to call533* for every element. This function534* takes 3 arguments (the element, the index and the array) and should535* return a boolean.536* @param {S=} opt_obj An optional "this" context for the function.537* @return {T|null} The last array element that passes the test, or null if no538* element is found.539* @template T,S540*/541goog.array.findRight = function(arr, f, opt_obj) {542var i = goog.array.findIndexRight(arr, f, opt_obj);543return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];544};545546547/**548* Search an array (in reverse order) for the last element that satisfies a549* given condition and return its index.550* @param {IArrayLike<T>|string} arr Array or array551* like object over which to iterate.552* @param {?function(this:S, T, number, ?) : boolean} f The function to call553* for every element. This function554* takes 3 arguments (the element, the index and the array) and should555* return a boolean.556* @param {S=} opt_obj An optional "this" context for the function.557* @return {number} The index of the last array element that passes the test,558* or -1 if no element is found.559* @template T,S560*/561goog.array.findIndexRight = function(arr, f, opt_obj) {562var l = arr.length; // must be fixed during loop... see docs563var arr2 = goog.isString(arr) ? arr.split('') : arr;564for (var i = l - 1; i >= 0; i--) {565if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {566return i;567}568}569return -1;570};571572573/**574* Whether the array contains the given object.575* @param {IArrayLike<?>|string} arr The array to test for the presence of the576* element.577* @param {*} obj The object for which to test.578* @return {boolean} true if obj is present.579*/580goog.array.contains = function(arr, obj) {581return goog.array.indexOf(arr, obj) >= 0;582};583584585/**586* Whether the array is empty.587* @param {IArrayLike<?>|string} arr The array to test.588* @return {boolean} true if empty.589*/590goog.array.isEmpty = function(arr) {591return arr.length == 0;592};593594595/**596* Clears the array.597* @param {IArrayLike<?>} arr Array or array like object to clear.598*/599goog.array.clear = function(arr) {600// For non real arrays we don't have the magic length so we delete the601// indices.602if (!goog.isArray(arr)) {603for (var i = arr.length - 1; i >= 0; i--) {604delete arr[i];605}606}607arr.length = 0;608};609610611/**612* Pushes an item into an array, if it's not already in the array.613* @param {Array<T>} arr Array into which to insert the item.614* @param {T} obj Value to add.615* @template T616*/617goog.array.insert = function(arr, obj) {618if (!goog.array.contains(arr, obj)) {619arr.push(obj);620}621};622623624/**625* Inserts an object at the given index of the array.626* @param {IArrayLike<?>} arr The array to modify.627* @param {*} obj The object to insert.628* @param {number=} opt_i The index at which to insert the object. If omitted,629* treated as 0. A negative index is counted from the end of the array.630*/631goog.array.insertAt = function(arr, obj, opt_i) {632goog.array.splice(arr, opt_i, 0, obj);633};634635636/**637* Inserts at the given index of the array, all elements of another array.638* @param {IArrayLike<?>} arr The array to modify.639* @param {IArrayLike<?>} elementsToAdd The array of elements to add.640* @param {number=} opt_i The index at which to insert the object. If omitted,641* treated as 0. A negative index is counted from the end of the array.642*/643goog.array.insertArrayAt = function(arr, elementsToAdd, opt_i) {644goog.partial(goog.array.splice, arr, opt_i, 0).apply(null, elementsToAdd);645};646647648/**649* Inserts an object into an array before a specified object.650* @param {Array<T>} arr The array to modify.651* @param {T} obj The object to insert.652* @param {T=} opt_obj2 The object before which obj should be inserted. If obj2653* is omitted or not found, obj is inserted at the end of the array.654* @template T655*/656goog.array.insertBefore = function(arr, obj, opt_obj2) {657var i;658if (arguments.length == 2 || (i = goog.array.indexOf(arr, opt_obj2)) < 0) {659arr.push(obj);660} else {661goog.array.insertAt(arr, obj, i);662}663};664665666/**667* Removes the first occurrence of a particular value from an array.668* @param {IArrayLike<T>} arr Array from which to remove669* value.670* @param {T} obj Object to remove.671* @return {boolean} True if an element was removed.672* @template T673*/674goog.array.remove = function(arr, obj) {675var i = goog.array.indexOf(arr, obj);676var rv;677if ((rv = i >= 0)) {678goog.array.removeAt(arr, i);679}680return rv;681};682683684/**685* Removes the last occurrence of a particular value from an array.686* @param {!IArrayLike<T>} arr Array from which to remove value.687* @param {T} obj Object to remove.688* @return {boolean} True if an element was removed.689* @template T690*/691goog.array.removeLast = function(arr, obj) {692var i = goog.array.lastIndexOf(arr, obj);693if (i >= 0) {694goog.array.removeAt(arr, i);695return true;696}697return false;698};699700701/**702* Removes from an array the element at index i703* @param {IArrayLike<?>} arr Array or array like object from which to704* remove value.705* @param {number} i The index to remove.706* @return {boolean} True if an element was removed.707*/708goog.array.removeAt = function(arr, i) {709goog.asserts.assert(arr.length != null);710711// use generic form of splice712// splice returns the removed items and if successful the length of that713// will be 1714return Array.prototype.splice.call(arr, i, 1).length == 1;715};716717718/**719* Removes the first value that satisfies the given condition.720* @param {IArrayLike<T>} arr Array or array721* like object over which to iterate.722* @param {?function(this:S, T, number, ?) : boolean} f The function to call723* for every element. This function724* takes 3 arguments (the element, the index and the array) and should725* return a boolean.726* @param {S=} opt_obj An optional "this" context for the function.727* @return {boolean} True if an element was removed.728* @template T,S729*/730goog.array.removeIf = function(arr, f, opt_obj) {731var i = goog.array.findIndex(arr, f, opt_obj);732if (i >= 0) {733goog.array.removeAt(arr, i);734return true;735}736return false;737};738739740/**741* Removes all values that satisfy the given condition.742* @param {IArrayLike<T>} arr Array or array743* like object over which to iterate.744* @param {?function(this:S, T, number, ?) : boolean} f The function to call745* for every element. This function746* takes 3 arguments (the element, the index and the array) and should747* return a boolean.748* @param {S=} opt_obj An optional "this" context for the function.749* @return {number} The number of items removed750* @template T,S751*/752goog.array.removeAllIf = function(arr, f, opt_obj) {753var removedCount = 0;754goog.array.forEachRight(arr, function(val, index) {755if (f.call(/** @type {?} */ (opt_obj), val, index, arr)) {756if (goog.array.removeAt(arr, index)) {757removedCount++;758}759}760});761return removedCount;762};763764765/**766* Returns a new array that is the result of joining the arguments. If arrays767* are passed then their items are added, however, if non-arrays are passed they768* will be added to the return array as is.769*770* Note that ArrayLike objects will be added as is, rather than having their771* items added.772*773* goog.array.concat([1, 2], [3, 4]) -> [1, 2, 3, 4]774* goog.array.concat(0, [1, 2]) -> [0, 1, 2]775* goog.array.concat([1, 2], null) -> [1, 2, null]776*777* There is bug in all current versions of IE (6, 7 and 8) where arrays created778* in an iframe become corrupted soon (not immediately) after the iframe is779* destroyed. This is common if loading data via goog.net.IframeIo, for example.780* This corruption only affects the concat method which will start throwing781* Catastrophic Errors (#-2147418113).782*783* See http://endoflow.com/scratch/corrupted-arrays.html for a test case.784*785* Internally goog.array should use this, so that all methods will continue to786* work on these broken array objects.787*788* @param {...*} var_args Items to concatenate. Arrays will have each item789* added, while primitives and objects will be added as is.790* @return {!Array<?>} The new resultant array.791*/792goog.array.concat = function(var_args) {793return Array.prototype.concat.apply([], arguments);794};795796797/**798* Returns a new array that contains the contents of all the arrays passed.799* @param {...!Array<T>} var_args800* @return {!Array<T>}801* @template T802*/803goog.array.join = function(var_args) {804return Array.prototype.concat.apply([], arguments);805};806807808/**809* Converts an object to an array.810* @param {IArrayLike<T>|string} object The object to convert to an811* array.812* @return {!Array<T>} The object converted into an array. If object has a813* length property, every property indexed with a non-negative number814* less than length will be included in the result. If object does not815* have a length property, an empty array will be returned.816* @template T817*/818goog.array.toArray = function(object) {819var length = object.length;820821// If length is not a number the following it false. This case is kept for822// backwards compatibility since there are callers that pass objects that are823// not array like.824if (length > 0) {825var rv = new Array(length);826for (var i = 0; i < length; i++) {827rv[i] = object[i];828}829return rv;830}831return [];832};833834835/**836* Does a shallow copy of an array.837* @param {IArrayLike<T>|string} arr Array or array-like object to838* clone.839* @return {!Array<T>} Clone of the input array.840* @template T841*/842goog.array.clone = goog.array.toArray;843844845/**846* Extends an array with another array, element, or "array like" object.847* This function operates 'in-place', it does not create a new Array.848*849* Example:850* var a = [];851* goog.array.extend(a, [0, 1]);852* a; // [0, 1]853* goog.array.extend(a, 2);854* a; // [0, 1, 2]855*856* @param {Array<VALUE>} arr1 The array to modify.857* @param {...(Array<VALUE>|VALUE)} var_args The elements or arrays of elements858* to add to arr1.859* @template VALUE860*/861goog.array.extend = function(arr1, var_args) {862for (var i = 1; i < arguments.length; i++) {863var arr2 = arguments[i];864if (goog.isArrayLike(arr2)) {865var len1 = arr1.length || 0;866var len2 = arr2.length || 0;867arr1.length = len1 + len2;868for (var j = 0; j < len2; j++) {869arr1[len1 + j] = arr2[j];870}871} else {872arr1.push(arr2);873}874}875};876877878/**879* Adds or removes elements from an array. This is a generic version of Array880* splice. This means that it might work on other objects similar to arrays,881* such as the arguments object.882*883* @param {IArrayLike<T>} arr The array to modify.884* @param {number|undefined} index The index at which to start changing the885* array. If not defined, treated as 0.886* @param {number} howMany How many elements to remove (0 means no removal. A887* value below 0 is treated as zero and so is any other non number. Numbers888* are floored).889* @param {...T} var_args Optional, additional elements to insert into the890* array.891* @return {!Array<T>} the removed elements.892* @template T893*/894goog.array.splice = function(arr, index, howMany, var_args) {895goog.asserts.assert(arr.length != null);896897return Array.prototype.splice.apply(arr, goog.array.slice(arguments, 1));898};899900901/**902* Returns a new array from a segment of an array. This is a generic version of903* Array slice. This means that it might work on other objects similar to904* arrays, such as the arguments object.905*906* @param {IArrayLike<T>|string} arr The array from907* which to copy a segment.908* @param {number} start The index of the first element to copy.909* @param {number=} opt_end The index after the last element to copy.910* @return {!Array<T>} A new array containing the specified segment of the911* original array.912* @template T913*/914goog.array.slice = function(arr, start, opt_end) {915goog.asserts.assert(arr.length != null);916917// passing 1 arg to slice is not the same as passing 2 where the second is918// null or undefined (in that case the second argument is treated as 0).919// we could use slice on the arguments object and then use apply instead of920// testing the length921if (arguments.length <= 2) {922return Array.prototype.slice.call(arr, start);923} else {924return Array.prototype.slice.call(arr, start, opt_end);925}926};927928929/**930* Removes all duplicates from an array (retaining only the first931* occurrence of each array element). This function modifies the932* array in place and doesn't change the order of the non-duplicate items.933*934* For objects, duplicates are identified as having the same unique ID as935* defined by {@link goog.getUid}.936*937* Alternatively you can specify a custom hash function that returns a unique938* value for each item in the array it should consider unique.939*940* Runtime: N,941* Worstcase space: 2N (no dupes)942*943* @param {IArrayLike<T>} arr The array from which to remove944* duplicates.945* @param {Array=} opt_rv An optional array in which to return the results,946* instead of performing the removal inplace. If specified, the original947* array will remain unchanged.948* @param {function(T):string=} opt_hashFn An optional function to use to949* apply to every item in the array. This function should return a unique950* value for each item in the array it should consider unique.951* @template T952*/953goog.array.removeDuplicates = function(arr, opt_rv, opt_hashFn) {954var returnArray = opt_rv || arr;955var defaultHashFn = function(item) {956// Prefix each type with a single character representing the type to957// prevent conflicting keys (e.g. true and 'true').958return goog.isObject(item) ? 'o' + goog.getUid(item) :959(typeof item).charAt(0) + item;960};961var hashFn = opt_hashFn || defaultHashFn;962963var seen = {}, cursorInsert = 0, cursorRead = 0;964while (cursorRead < arr.length) {965var current = arr[cursorRead++];966var key = hashFn(current);967if (!Object.prototype.hasOwnProperty.call(seen, key)) {968seen[key] = true;969returnArray[cursorInsert++] = current;970}971}972returnArray.length = cursorInsert;973};974975976/**977* Searches the specified array for the specified target using the binary978* search algorithm. If no opt_compareFn is specified, elements are compared979* using <code>goog.array.defaultCompare</code>, which compares the elements980* using the built in < and > operators. This will produce the expected981* behavior for homogeneous arrays of String(s) and Number(s). The array982* specified <b>must</b> be sorted in ascending order (as defined by the983* comparison function). If the array is not sorted, results are undefined.984* If the array contains multiple instances of the specified target value, any985* of these instances may be found.986*987* Runtime: O(log n)988*989* @param {IArrayLike<VALUE>} arr The array to be searched.990* @param {TARGET} target The sought value.991* @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison992* function by which the array is ordered. Should take 2 arguments to993* compare, and return a negative number, zero, or a positive number994* depending on whether the first argument is less than, equal to, or995* greater than the second.996* @return {number} Lowest index of the target value if found, otherwise997* (-(insertion point) - 1). The insertion point is where the value should998* be inserted into arr to preserve the sorted property. Return value >= 0999* iff target is found.1000* @template TARGET, VALUE1001*/1002goog.array.binarySearch = function(arr, target, opt_compareFn) {1003return goog.array.binarySearch_(1004arr, opt_compareFn || goog.array.defaultCompare, false /* isEvaluator */,1005target);1006};100710081009/**1010* Selects an index in the specified array using the binary search algorithm.1011* The evaluator receives an element and determines whether the desired index1012* is before, at, or after it. The evaluator must be consistent (formally,1013* goog.array.map(goog.array.map(arr, evaluator, opt_obj), goog.math.sign)1014* must be monotonically non-increasing).1015*1016* Runtime: O(log n)1017*1018* @param {IArrayLike<VALUE>} arr The array to be searched.1019* @param {function(this:THIS, VALUE, number, ?): number} evaluator1020* Evaluator function that receives 3 arguments (the element, the index and1021* the array). Should return a negative number, zero, or a positive number1022* depending on whether the desired index is before, at, or after the1023* element passed to it.1024* @param {THIS=} opt_obj The object to be used as the value of 'this'1025* within evaluator.1026* @return {number} Index of the leftmost element matched by the evaluator, if1027* such exists; otherwise (-(insertion point) - 1). The insertion point is1028* the index of the first element for which the evaluator returns negative,1029* or arr.length if no such element exists. The return value is non-negative1030* iff a match is found.1031* @template THIS, VALUE1032*/1033goog.array.binarySelect = function(arr, evaluator, opt_obj) {1034return goog.array.binarySearch_(1035arr, evaluator, true /* isEvaluator */, undefined /* opt_target */,1036opt_obj);1037};103810391040/**1041* Implementation of a binary search algorithm which knows how to use both1042* comparison functions and evaluators. If an evaluator is provided, will call1043* the evaluator with the given optional data object, conforming to the1044* interface defined in binarySelect. Otherwise, if a comparison function is1045* provided, will call the comparison function against the given data object.1046*1047* This implementation purposefully does not use goog.bind or goog.partial for1048* performance reasons.1049*1050* Runtime: O(log n)1051*1052* @param {IArrayLike<?>} arr The array to be searched.1053* @param {function(?, ?, ?): number | function(?, ?): number} compareFn1054* Either an evaluator or a comparison function, as defined by binarySearch1055* and binarySelect above.1056* @param {boolean} isEvaluator Whether the function is an evaluator or a1057* comparison function.1058* @param {?=} opt_target If the function is a comparison function, then1059* this is the target to binary search for.1060* @param {Object=} opt_selfObj If the function is an evaluator, this is an1061* optional this object for the evaluator.1062* @return {number} Lowest index of the target value if found, otherwise1063* (-(insertion point) - 1). The insertion point is where the value should1064* be inserted into arr to preserve the sorted property. Return value >= 01065* iff target is found.1066* @private1067*/1068goog.array.binarySearch_ = function(1069arr, compareFn, isEvaluator, opt_target, opt_selfObj) {1070var left = 0; // inclusive1071var right = arr.length; // exclusive1072var found;1073while (left < right) {1074var middle = (left + right) >> 1;1075var compareResult;1076if (isEvaluator) {1077compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);1078} else {1079// NOTE(dimvar): To avoid this cast, we'd have to use function overloading1080// for the type of binarySearch_, which the type system can't express yet.1081compareResult = /** @type {function(?, ?): number} */ (compareFn)(1082opt_target, arr[middle]);1083}1084if (compareResult > 0) {1085left = middle + 1;1086} else {1087right = middle;1088// We are looking for the lowest index so we can't return immediately.1089found = !compareResult;1090}1091}1092// left is the index if found, or the insertion point otherwise.1093// ~left is a shorthand for -left - 1.1094return found ? left : ~left;1095};109610971098/**1099* Sorts the specified array into ascending order. If no opt_compareFn is1100* specified, elements are compared using1101* <code>goog.array.defaultCompare</code>, which compares the elements using1102* the built in < and > operators. This will produce the expected behavior1103* for homogeneous arrays of String(s) and Number(s), unlike the native sort,1104* but will give unpredictable results for heterogeneous lists of strings and1105* numbers with different numbers of digits.1106*1107* This sort is not guaranteed to be stable.1108*1109* Runtime: Same as <code>Array.prototype.sort</code>1110*1111* @param {Array<T>} arr The array to be sorted.1112* @param {?function(T,T):number=} opt_compareFn Optional comparison1113* function by which the1114* array is to be ordered. Should take 2 arguments to compare, and return a1115* negative number, zero, or a positive number depending on whether the1116* first argument is less than, equal to, or greater than the second.1117* @template T1118*/1119goog.array.sort = function(arr, opt_compareFn) {1120// TODO(arv): Update type annotation since null is not accepted.1121arr.sort(opt_compareFn || goog.array.defaultCompare);1122};112311241125/**1126* Sorts the specified array into ascending order in a stable way. If no1127* opt_compareFn is specified, elements are compared using1128* <code>goog.array.defaultCompare</code>, which compares the elements using1129* the built in < and > operators. This will produce the expected behavior1130* for homogeneous arrays of String(s) and Number(s).1131*1132* Runtime: Same as <code>Array.prototype.sort</code>, plus an additional1133* O(n) overhead of copying the array twice.1134*1135* @param {Array<T>} arr The array to be sorted.1136* @param {?function(T, T): number=} opt_compareFn Optional comparison function1137* by which the array is to be ordered. Should take 2 arguments to compare,1138* and return a negative number, zero, or a positive number depending on1139* whether the first argument is less than, equal to, or greater than the1140* second.1141* @template T1142*/1143goog.array.stableSort = function(arr, opt_compareFn) {1144var compArr = new Array(arr.length);1145for (var i = 0; i < arr.length; i++) {1146compArr[i] = {index: i, value: arr[i]};1147}1148var valueCompareFn = opt_compareFn || goog.array.defaultCompare;1149function stableCompareFn(obj1, obj2) {1150return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;1151}1152goog.array.sort(compArr, stableCompareFn);1153for (var i = 0; i < arr.length; i++) {1154arr[i] = compArr[i].value;1155}1156};115711581159/**1160* Sort the specified array into ascending order based on item keys1161* returned by the specified key function.1162* If no opt_compareFn is specified, the keys are compared in ascending order1163* using <code>goog.array.defaultCompare</code>.1164*1165* Runtime: O(S(f(n)), where S is runtime of <code>goog.array.sort</code>1166* and f(n) is runtime of the key function.1167*1168* @param {Array<T>} arr The array to be sorted.1169* @param {function(T): K} keyFn Function taking array element and returning1170* a key used for sorting this element.1171* @param {?function(K, K): number=} opt_compareFn Optional comparison function1172* by which the keys are to be ordered. Should take 2 arguments to compare,1173* and return a negative number, zero, or a positive number depending on1174* whether the first argument is less than, equal to, or greater than the1175* second.1176* @template T,K1177*/1178goog.array.sortByKey = function(arr, keyFn, opt_compareFn) {1179var keyCompareFn = opt_compareFn || goog.array.defaultCompare;1180goog.array.sort(1181arr, function(a, b) { return keyCompareFn(keyFn(a), keyFn(b)); });1182};118311841185/**1186* Sorts an array of objects by the specified object key and compare1187* function. If no compare function is provided, the key values are1188* compared in ascending order using <code>goog.array.defaultCompare</code>.1189* This won't work for keys that get renamed by the compiler. So use1190* {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.1191* @param {Array<Object>} arr An array of objects to sort.1192* @param {string} key The object key to sort by.1193* @param {Function=} opt_compareFn The function to use to compare key1194* values.1195*/1196goog.array.sortObjectsByKey = function(arr, key, opt_compareFn) {1197goog.array.sortByKey(arr, function(obj) { return obj[key]; }, opt_compareFn);1198};119912001201/**1202* Tells if the array is sorted.1203* @param {!Array<T>} arr The array.1204* @param {?function(T,T):number=} opt_compareFn Function to compare the1205* array elements.1206* Should take 2 arguments to compare, and return a negative number, zero,1207* or a positive number depending on whether the first argument is less1208* than, equal to, or greater than the second.1209* @param {boolean=} opt_strict If true no equal elements are allowed.1210* @return {boolean} Whether the array is sorted.1211* @template T1212*/1213goog.array.isSorted = function(arr, opt_compareFn, opt_strict) {1214var compare = opt_compareFn || goog.array.defaultCompare;1215for (var i = 1; i < arr.length; i++) {1216var compareResult = compare(arr[i - 1], arr[i]);1217if (compareResult > 0 || compareResult == 0 && opt_strict) {1218return false;1219}1220}1221return true;1222};122312241225/**1226* Compares two arrays for equality. Two arrays are considered equal if they1227* have the same length and their corresponding elements are equal according to1228* the comparison function.1229*1230* @param {IArrayLike<?>} arr1 The first array to compare.1231* @param {IArrayLike<?>} arr2 The second array to compare.1232* @param {Function=} opt_equalsFn Optional comparison function.1233* Should take 2 arguments to compare, and return true if the arguments1234* are equal. Defaults to {@link goog.array.defaultCompareEquality} which1235* compares the elements using the built-in '===' operator.1236* @return {boolean} Whether the two arrays are equal.1237*/1238goog.array.equals = function(arr1, arr2, opt_equalsFn) {1239if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||1240arr1.length != arr2.length) {1241return false;1242}1243var l = arr1.length;1244var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality;1245for (var i = 0; i < l; i++) {1246if (!equalsFn(arr1[i], arr2[i])) {1247return false;1248}1249}1250return true;1251};125212531254/**1255* 3-way array compare function.1256* @param {!IArrayLike<VALUE>} arr1 The first array to1257* compare.1258* @param {!IArrayLike<VALUE>} arr2 The second array to1259* compare.1260* @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison1261* function by which the array is to be ordered. Should take 2 arguments to1262* compare, and return a negative number, zero, or a positive number1263* depending on whether the first argument is less than, equal to, or1264* greater than the second.1265* @return {number} Negative number, zero, or a positive number depending on1266* whether the first argument is less than, equal to, or greater than the1267* second.1268* @template VALUE1269*/1270goog.array.compare3 = function(arr1, arr2, opt_compareFn) {1271var compare = opt_compareFn || goog.array.defaultCompare;1272var l = Math.min(arr1.length, arr2.length);1273for (var i = 0; i < l; i++) {1274var result = compare(arr1[i], arr2[i]);1275if (result != 0) {1276return result;1277}1278}1279return goog.array.defaultCompare(arr1.length, arr2.length);1280};128112821283/**1284* Compares its two arguments for order, using the built in < and >1285* operators.1286* @param {VALUE} a The first object to be compared.1287* @param {VALUE} b The second object to be compared.1288* @return {number} A negative number, zero, or a positive number as the first1289* argument is less than, equal to, or greater than the second,1290* respectively.1291* @template VALUE1292*/1293goog.array.defaultCompare = function(a, b) {1294return a > b ? 1 : a < b ? -1 : 0;1295};129612971298/**1299* Compares its two arguments for inverse order, using the built in < and >1300* operators.1301* @param {VALUE} a The first object to be compared.1302* @param {VALUE} b The second object to be compared.1303* @return {number} A negative number, zero, or a positive number as the first1304* argument is greater than, equal to, or less than the second,1305* respectively.1306* @template VALUE1307*/1308goog.array.inverseDefaultCompare = function(a, b) {1309return -goog.array.defaultCompare(a, b);1310};131113121313/**1314* Compares its two arguments for equality, using the built in === operator.1315* @param {*} a The first object to compare.1316* @param {*} b The second object to compare.1317* @return {boolean} True if the two arguments are equal, false otherwise.1318*/1319goog.array.defaultCompareEquality = function(a, b) {1320return a === b;1321};132213231324/**1325* Inserts a value into a sorted array. The array is not modified if the1326* value is already present.1327* @param {IArrayLike<VALUE>} array The array to modify.1328* @param {VALUE} value The object to insert.1329* @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison1330* function by which the array is ordered. Should take 2 arguments to1331* compare, and return a negative number, zero, or a positive number1332* depending on whether the first argument is less than, equal to, or1333* greater than the second.1334* @return {boolean} True if an element was inserted.1335* @template VALUE1336*/1337goog.array.binaryInsert = function(array, value, opt_compareFn) {1338var index = goog.array.binarySearch(array, value, opt_compareFn);1339if (index < 0) {1340goog.array.insertAt(array, value, -(index + 1));1341return true;1342}1343return false;1344};134513461347/**1348* Removes a value from a sorted array.1349* @param {!IArrayLike<VALUE>} array The array to modify.1350* @param {VALUE} value The object to remove.1351* @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison1352* function by which the array is ordered. Should take 2 arguments to1353* compare, and return a negative number, zero, or a positive number1354* depending on whether the first argument is less than, equal to, or1355* greater than the second.1356* @return {boolean} True if an element was removed.1357* @template VALUE1358*/1359goog.array.binaryRemove = function(array, value, opt_compareFn) {1360var index = goog.array.binarySearch(array, value, opt_compareFn);1361return (index >= 0) ? goog.array.removeAt(array, index) : false;1362};136313641365/**1366* Splits an array into disjoint buckets according to a splitting function.1367* @param {Array<T>} array The array.1368* @param {function(this:S, T,number,Array<T>):?} sorter Function to call for1369* every element. This takes 3 arguments (the element, the index and the1370* array) and must return a valid object key (a string, number, etc), or1371* undefined, if that object should not be placed in a bucket.1372* @param {S=} opt_obj The object to be used as the value of 'this' within1373* sorter.1374* @return {!Object} An object, with keys being all of the unique return values1375* of sorter, and values being arrays containing the items for1376* which the splitter returned that key.1377* @template T,S1378*/1379goog.array.bucket = function(array, sorter, opt_obj) {1380var buckets = {};13811382for (var i = 0; i < array.length; i++) {1383var value = array[i];1384var key = sorter.call(/** @type {?} */ (opt_obj), value, i, array);1385if (goog.isDef(key)) {1386// Push the value to the right bucket, creating it if necessary.1387var bucket = buckets[key] || (buckets[key] = []);1388bucket.push(value);1389}1390}13911392return buckets;1393};139413951396/**1397* Creates a new object built from the provided array and the key-generation1398* function.1399* @param {IArrayLike<T>} arr Array or array like object over1400* which to iterate whose elements will be the values in the new object.1401* @param {?function(this:S, T, number, ?) : string} keyFunc The function to1402* call for every element. This function takes 3 arguments (the element, the1403* index and the array) and should return a string that will be used as the1404* key for the element in the new object. If the function returns the same1405* key for more than one element, the value for that key is1406* implementation-defined.1407* @param {S=} opt_obj The object to be used as the value of 'this'1408* within keyFunc.1409* @return {!Object<T>} The new object.1410* @template T,S1411*/1412goog.array.toObject = function(arr, keyFunc, opt_obj) {1413var ret = {};1414goog.array.forEach(arr, function(element, index) {1415ret[keyFunc.call(/** @type {?} */ (opt_obj), element, index, arr)] =1416element;1417});1418return ret;1419};142014211422/**1423* Creates a range of numbers in an arithmetic progression.1424*1425* Range takes 1, 2, or 3 arguments:1426* <pre>1427* range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]1428* range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]1429* range(-2, -5, -1) produces [-2, -3, -4]1430* range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.1431* </pre>1432*1433* @param {number} startOrEnd The starting value of the range if an end argument1434* is provided. Otherwise, the start value is 0, and this is the end value.1435* @param {number=} opt_end The optional end value of the range.1436* @param {number=} opt_step The step size between range values. Defaults to 11437* if opt_step is undefined or 0.1438* @return {!Array<number>} An array of numbers for the requested range. May be1439* an empty array if adding the step would not converge toward the end1440* value.1441*/1442goog.array.range = function(startOrEnd, opt_end, opt_step) {1443var array = [];1444var start = 0;1445var end = startOrEnd;1446var step = opt_step || 1;1447if (opt_end !== undefined) {1448start = startOrEnd;1449end = opt_end;1450}14511452if (step * (end - start) < 0) {1453// Sign mismatch: start + step will never reach the end value.1454return [];1455}14561457if (step > 0) {1458for (var i = start; i < end; i += step) {1459array.push(i);1460}1461} else {1462for (var i = start; i > end; i += step) {1463array.push(i);1464}1465}1466return array;1467};146814691470/**1471* Returns an array consisting of the given value repeated N times.1472*1473* @param {VALUE} value The value to repeat.1474* @param {number} n The repeat count.1475* @return {!Array<VALUE>} An array with the repeated value.1476* @template VALUE1477*/1478goog.array.repeat = function(value, n) {1479var array = [];1480for (var i = 0; i < n; i++) {1481array[i] = value;1482}1483return array;1484};148514861487/**1488* Returns an array consisting of every argument with all arrays1489* expanded in-place recursively.1490*1491* @param {...*} var_args The values to flatten.1492* @return {!Array<?>} An array containing the flattened values.1493*/1494goog.array.flatten = function(var_args) {1495var CHUNK_SIZE = 8192;14961497var result = [];1498for (var i = 0; i < arguments.length; i++) {1499var element = arguments[i];1500if (goog.isArray(element)) {1501for (var c = 0; c < element.length; c += CHUNK_SIZE) {1502var chunk = goog.array.slice(element, c, c + CHUNK_SIZE);1503var recurseResult = goog.array.flatten.apply(null, chunk);1504for (var r = 0; r < recurseResult.length; r++) {1505result.push(recurseResult[r]);1506}1507}1508} else {1509result.push(element);1510}1511}1512return result;1513};151415151516/**1517* Rotates an array in-place. After calling this method, the element at1518* index i will be the element previously at index (i - n) %1519* array.length, for all values of i between 0 and array.length - 1,1520* inclusive.1521*1522* For example, suppose list comprises [t, a, n, k, s]. After invoking1523* rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].1524*1525* @param {!Array<T>} array The array to rotate.1526* @param {number} n The amount to rotate.1527* @return {!Array<T>} The array.1528* @template T1529*/1530goog.array.rotate = function(array, n) {1531goog.asserts.assert(array.length != null);15321533if (array.length) {1534n %= array.length;1535if (n > 0) {1536Array.prototype.unshift.apply(array, array.splice(-n, n));1537} else if (n < 0) {1538Array.prototype.push.apply(array, array.splice(0, -n));1539}1540}1541return array;1542};154315441545/**1546* Moves one item of an array to a new position keeping the order of the rest1547* of the items. Example use case: keeping a list of JavaScript objects1548* synchronized with the corresponding list of DOM elements after one of the1549* elements has been dragged to a new position.1550* @param {!IArrayLike<?>} arr The array to modify.1551* @param {number} fromIndex Index of the item to move between 0 and1552* {@code arr.length - 1}.1553* @param {number} toIndex Target index between 0 and {@code arr.length - 1}.1554*/1555goog.array.moveItem = function(arr, fromIndex, toIndex) {1556goog.asserts.assert(fromIndex >= 0 && fromIndex < arr.length);1557goog.asserts.assert(toIndex >= 0 && toIndex < arr.length);1558// Remove 1 item at fromIndex.1559var removedItems = Array.prototype.splice.call(arr, fromIndex, 1);1560// Insert the removed item at toIndex.1561Array.prototype.splice.call(arr, toIndex, 0, removedItems[0]);1562// We don't use goog.array.insertAt and goog.array.removeAt, because they're1563// significantly slower than splice.1564};156515661567/**1568* Creates a new array for which the element at position i is an array of the1569* ith element of the provided arrays. The returned array will only be as long1570* as the shortest array provided; additional values are ignored. For example,1571* the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].1572*1573* This is similar to the zip() function in Python. See {@link1574* http://docs.python.org/library/functions.html#zip}1575*1576* @param {...!IArrayLike<?>} var_args Arrays to be combined.1577* @return {!Array<!Array<?>>} A new array of arrays created from1578* provided arrays.1579*/1580goog.array.zip = function(var_args) {1581if (!arguments.length) {1582return [];1583}1584var result = [];1585var minLen = arguments[0].length;1586for (var i = 1; i < arguments.length; i++) {1587if (arguments[i].length < minLen) {1588minLen = arguments[i].length;1589}1590}1591for (var i = 0; i < minLen; i++) {1592var value = [];1593for (var j = 0; j < arguments.length; j++) {1594value.push(arguments[j][i]);1595}1596result.push(value);1597}1598return result;1599};160016011602/**1603* Shuffles the values in the specified array using the Fisher-Yates in-place1604* shuffle (also known as the Knuth Shuffle). By default, calls Math.random()1605* and so resets the state of that random number generator. Similarly, may reset1606* the state of the any other specified random number generator.1607*1608* Runtime: O(n)1609*1610* @param {!Array<?>} arr The array to be shuffled.1611* @param {function():number=} opt_randFn Optional random function to use for1612* shuffling.1613* Takes no arguments, and returns a random number on the interval [0, 1).1614* Defaults to Math.random() using JavaScript's built-in Math library.1615*/1616goog.array.shuffle = function(arr, opt_randFn) {1617var randFn = opt_randFn || Math.random;16181619for (var i = arr.length - 1; i > 0; i--) {1620// Choose a random array index in [0, i] (inclusive with i).1621var j = Math.floor(randFn() * (i + 1));16221623var tmp = arr[i];1624arr[i] = arr[j];1625arr[j] = tmp;1626}1627};162816291630/**1631* Returns a new array of elements from arr, based on the indexes of elements1632* provided by index_arr. For example, the result of index copying1633* ['a', 'b', 'c'] with index_arr [1,0,0,2] is ['b', 'a', 'a', 'c'].1634*1635* @param {!Array<T>} arr The array to get a indexed copy from.1636* @param {!Array<number>} index_arr An array of indexes to get from arr.1637* @return {!Array<T>} A new array of elements from arr in index_arr order.1638* @template T1639*/1640goog.array.copyByIndex = function(arr, index_arr) {1641var result = [];1642goog.array.forEach(index_arr, function(index) { result.push(arr[index]); });1643return result;1644};164516461647/**1648* Maps each element of the input array into zero or more elements of the output1649* array.1650*1651* @param {!IArrayLike<VALUE>|string} arr Array or array like object1652* over which to iterate.1653* @param {function(this:THIS, VALUE, number, ?): !Array<RESULT>} f The function1654* to call for every element. This function takes 3 arguments (the element,1655* the index and the array) and should return an array. The result will be1656* used to extend a new array.1657* @param {THIS=} opt_obj The object to be used as the value of 'this' within f.1658* @return {!Array<RESULT>} a new array with the concatenation of all arrays1659* returned from f.1660* @template THIS, VALUE, RESULT1661*/1662goog.array.concatMap = function(arr, f, opt_obj) {1663return goog.array.concat.apply([], goog.array.map(arr, f, opt_obj));1664};166516661667