Path: blob/trunk/third_party/closure/goog/array/array.js
4503 views
/**1* @license2* Copyright The Closure Library Authors.3* SPDX-License-Identifier: Apache-2.04*/56/**7* @fileoverview Utilities for manipulating arrays.8*/91011goog.module('goog.array');12goog.module.declareLegacyNamespace();1314const asserts = goog.require('goog.asserts');15const utils = goog.require('goog.utils');161718/**19* @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should20* rely on Array.prototype functions, if available.21*22* The Array.prototype functions can be defined by external libraries like23* Prototype and setting this flag to false forces closure to use its own24* goog.array implementation.25*26* If your javascript can be loaded by a third party site and you are wary about27* relying on the prototype functions, specify28* "--define goog.NATIVE_ARRAY_PROTOTYPES=false" to the JSCompiler.29*30* Setting goog.TRUSTED_SITE to false will automatically set31* NATIVE_ARRAY_PROTOTYPES to false.32*/33goog.NATIVE_ARRAY_PROTOTYPES =34goog.define('goog.NATIVE_ARRAY_PROTOTYPES', true);353637/**38* @define {boolean} If true, JSCompiler will use the native implementation of39* array functions where appropriate (e.g., `Array#filter`) and remove the40* unused pure JS implementation.41*/42const ASSUME_NATIVE_FUNCTIONS = goog.define(43'goog.array.ASSUME_NATIVE_FUNCTIONS', goog.FEATURESET_YEAR > 2012);44exports.ASSUME_NATIVE_FUNCTIONS = ASSUME_NATIVE_FUNCTIONS;454647/**48* Returns the last element in an array without removing it.49* Same as {@link goog.array.last}.50* @param {IArrayLike<T>|string} array The array.51* @return {T} Last item in array.52* @template T53*/54function peek(array) {55return array[array.length - 1];56}57exports.peek = peek;585960/**61* Returns the last element in an array without removing it.62* Same as {@link goog.array.peek}.63* @param {IArrayLike<T>|string} array The array.64* @return {T} Last item in array.65* @template T66*/67exports.last = peek;6869// NOTE(arv): Since most of the array functions are generic it allows you to70// pass an array-like object. Strings have a length and are considered array-71// like. However, the 'in' operator does not work on strings so we cannot just72// use the array path even if the browser supports indexing into strings. We73// therefore end up splitting the string.747576/**77* Returns the index of the first element of an array with a specified value, or78* -1 if the element is not present in the array.79*80* See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}81*82* @param {IArrayLike<T>|string} arr The array to be searched.83* @param {T} obj The object for which we are searching.84* @param {number=} opt_fromIndex The index at which to start the search. If85* omitted the search starts at index 0.86* @return {number} The index of the first matching array element.87* @template T88*/89const indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&90(ASSUME_NATIVE_FUNCTIONS || Array.prototype.indexOf) ?91function(arr, obj, opt_fromIndex) {92asserts.assert(arr.length != null);9394return Array.prototype.indexOf.call(arr, obj, opt_fromIndex);95} :96function(arr, obj, opt_fromIndex) {97const fromIndex = opt_fromIndex == null ?980 :99(opt_fromIndex < 0 ? Math.max(0, arr.length + opt_fromIndex) :100opt_fromIndex);101102if (typeof arr === 'string') {103// Array.prototype.indexOf uses === so only strings should be found.104if (typeof obj !== 'string' || obj.length != 1) {105return -1;106}107return arr.indexOf(obj, fromIndex);108}109110for (let i = fromIndex; i < arr.length; i++) {111if (i in arr && arr[i] === obj) return i;112}113return -1;114};115exports.indexOf = indexOf;116117118/**119* Returns the index of the last element of an array with a specified value, or120* -1 if the element is not present in the array.121*122* See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof}123*124* @param {!IArrayLike<T>|string} arr The array to be searched.125* @param {T} obj The object for which we are searching.126* @param {?number=} opt_fromIndex The index at which to start the search. If127* omitted the search starts at the end of the array.128* @return {number} The index of the last matching array element.129* @template T130*/131const lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&132(ASSUME_NATIVE_FUNCTIONS || Array.prototype.lastIndexOf) ?133function(arr, obj, opt_fromIndex) {134asserts.assert(arr.length != null);135136// Firefox treats undefined and null as 0 in the fromIndex argument which137// leads it to always return -1138const fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;139return Array.prototype.lastIndexOf.call(arr, obj, fromIndex);140} :141function(arr, obj, opt_fromIndex) {142let fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;143144if (fromIndex < 0) {145fromIndex = Math.max(0, arr.length + fromIndex);146}147148if (typeof arr === 'string') {149// Array.prototype.lastIndexOf uses === so only strings should be found.150if (typeof obj !== 'string' || obj.length != 1) {151return -1;152}153return arr.lastIndexOf(obj, fromIndex);154}155156for (let i = fromIndex; i >= 0; i--) {157if (i in arr && arr[i] === obj) return i;158}159return -1;160};161exports.lastIndexOf = lastIndexOf;162163164/**165* Calls a function for each element in an array. Skips holes in the array.166* See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}167*168* @param {IArrayLike<T>|string} arr Array or array like object over169* which to iterate.170* @param {?function(this: S, T, number, ?): ?} f The function to call for every171* element. This function takes 3 arguments (the element, the index and the172* array). The return value is ignored.173* @param {S=} opt_obj The object to be used as the value of 'this' within f.174* @template T,S175*/176const forEach = goog.NATIVE_ARRAY_PROTOTYPES &&177(ASSUME_NATIVE_FUNCTIONS || Array.prototype.forEach) ?178function(arr, f, opt_obj) {179asserts.assert(arr.length != null);180181Array.prototype.forEach.call(arr, f, opt_obj);182} :183function(arr, f, opt_obj) {184const l = arr.length; // must be fixed during loop... see docs185const arr2 = (typeof arr === 'string') ? arr.split('') : arr;186for (let i = 0; i < l; i++) {187if (i in arr2) {188f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);189}190}191};192exports.forEach = forEach;193194195/**196* Calls a function for each element in an array, starting from the last197* element rather than the first.198*199* @param {IArrayLike<T>|string} arr Array or array200* like object over which to iterate.201* @param {?function(this: S, T, number, ?): ?} f The function to call for every202* element. This function203* takes 3 arguments (the element, the index and the array). The return204* value is ignored.205* @param {S=} opt_obj The object to be used as the value of 'this'206* within f.207* @template T,S208*/209function forEachRight(arr, f, opt_obj) {210const l = arr.length; // must be fixed during loop... see docs211const arr2 = (typeof arr === 'string') ? arr.split('') : arr;212for (let i = l - 1; i >= 0; --i) {213if (i in arr2) {214f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);215}216}217}218exports.forEachRight = forEachRight;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*/240const filter = goog.NATIVE_ARRAY_PROTOTYPES &&241(ASSUME_NATIVE_FUNCTIONS || Array.prototype.filter) ?242function(arr, f, opt_obj) {243asserts.assert(arr.length != null);244245return Array.prototype.filter.call(arr, f, opt_obj);246} :247function(arr, f, opt_obj) {248const l = arr.length; // must be fixed during loop... see docs249const res = [];250let resLength = 0;251const arr2 = (typeof arr === 'string') ? arr.split('') : arr;252for (let i = 0; i < l; i++) {253if (i in arr2) {254const 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};262exports.filter = filter;263264265/**266* Calls a function for each element in an array and inserts the result into a267* new array.268*269* See {@link http://tinyurl.com/developer-mozilla-org-array-map}270*271* @param {IArrayLike<VALUE>|string} arr Array or array like object272* over which to iterate.273* @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call274* for every element. This function takes 3 arguments (the element,275* the index and the array) and should return something. The result will be276* inserted into a new array.277* @param {THIS=} opt_obj The object to be used as the value of 'this' within f.278* @return {!Array<RESULT>} a new array with the results from f.279* @template THIS, VALUE, RESULT280*/281const map = goog.NATIVE_ARRAY_PROTOTYPES &&282(ASSUME_NATIVE_FUNCTIONS || Array.prototype.map) ?283function(arr, f, opt_obj) {284asserts.assert(arr.length != null);285286return Array.prototype.map.call(arr, f, opt_obj);287} :288function(arr, f, opt_obj) {289const l = arr.length; // must be fixed during loop... see docs290const res = new Array(l);291const arr2 = (typeof arr === 'string') ? arr.split('') : arr;292for (let i = 0; i < l; i++) {293if (i in arr2) {294res[i] = f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);295}296}297return res;298};299exports.map = map;300301302/**303* Passes every element of an array into a function and accumulates the result.304*305* See {@link http://tinyurl.com/developer-mozilla-org-array-reduce}306* Note that this implementation differs from the native Array.prototype.reduce307* in that the initial value is assumed to be defined (the MDN docs linked above308* recommend not omitting this parameter, although it is technically optional).309*310* For example:311* var a = [1, 2, 3, 4];312* reduce(a, function(r, v, i, arr) {return r + v;}, 0);313* returns 10314*315* @param {IArrayLike<T>|string} arr Array or array316* like object over which to iterate.317* @param {function(this:S, R, T, number, ?) : R} f The function to call for318* every element. This function319* takes 4 arguments (the function's previous result or the initial value,320* the value of the current array element, the current array index, and the321* array itself)322* function(previousValue, currentValue, index, array).323* @param {?} val The initial value to pass into the function on the first call.324* @param {S=} opt_obj The object to be used as the value of 'this'325* within f.326* @return {R} Result of evaluating f repeatedly across the values of the array.327* @template T,S,R328*/329const reduce = goog.NATIVE_ARRAY_PROTOTYPES &&330(ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduce) ?331function(arr, f, val, opt_obj) {332asserts.assert(arr.length != null);333if (opt_obj) {334f = utils.bind(f, opt_obj);335}336return Array.prototype.reduce.call(arr, f, val);337} :338function(arr, f, val, opt_obj) {339let rval = val;340forEach(arr, function(val, index) {341rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);342});343return rval;344};345exports.reduce = reduce;346347348/**349* Passes every element of an array into a function and accumulates the result,350* starting from the last element and working towards the first.351*352* See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright}353*354* For example:355* var a = ['a', 'b', 'c'];356* reduceRight(a, function(r, v, i, arr) {return r + v;}, '');357* returns 'cba'358*359* @param {IArrayLike<T>|string} arr Array or array360* like object over which to iterate.361* @param {?function(this:S, R, T, number, ?) : R} f The function to call for362* every element. This function363* takes 4 arguments (the function's previous result or the initial value,364* the value of the current array element, the current array index, and the365* array itself)366* function(previousValue, currentValue, index, array).367* @param {?} val The initial value to pass into the function on the first call.368* @param {S=} opt_obj The object to be used as the value of 'this'369* within f.370* @return {R} Object returned as a result of evaluating f repeatedly across the371* values of the array.372* @template T,S,R373*/374const reduceRight = goog.NATIVE_ARRAY_PROTOTYPES &&375(ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduceRight) ?376function(arr, f, val, opt_obj) {377asserts.assert(arr.length != null);378asserts.assert(f != null);379if (opt_obj) {380f = utils.bind(f, opt_obj);381}382return Array.prototype.reduceRight.call(arr, f, val);383} :384function(arr, f, val, opt_obj) {385let rval = val;386forEachRight(arr, function(val, index) {387rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);388});389return rval;390};391exports.reduceRight = reduceRight;392393394/**395* Calls f for each element of an array. If any call returns true, some()396* returns true (without checking the remaining elements). If all calls397* return false, some() returns false.398*399* See {@link http://tinyurl.com/developer-mozilla-org-array-some}400*401* @param {IArrayLike<T>|string} arr Array or array402* like object over which to iterate.403* @param {?function(this:S, T, number, ?) : boolean} f The function to call for404* for every element. This function takes 3 arguments (the element, the405* index and the array) and should return a boolean.406* @param {S=} opt_obj The object to be used as the value of 'this'407* within f.408* @return {boolean} true if any element passes the test.409* @template T,S410*/411const some = goog.NATIVE_ARRAY_PROTOTYPES &&412(ASSUME_NATIVE_FUNCTIONS || Array.prototype.some) ?413function(arr, f, opt_obj) {414asserts.assert(arr.length != null);415416return Array.prototype.some.call(arr, f, opt_obj);417} :418function(arr, f, opt_obj) {419const l = arr.length; // must be fixed during loop... see docs420const arr2 = (typeof arr === 'string') ? arr.split('') : arr;421for (let i = 0; i < l; i++) {422if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {423return true;424}425}426return false;427};428exports.some = some;429430431/**432* Call f for each element of an array. If all calls return true, every()433* returns true. If any call returns false, every() returns false and434* does not continue to check the remaining elements.435*436* See {@link http://tinyurl.com/developer-mozilla-org-array-every}437*438* @param {IArrayLike<T>|string} arr Array or array439* like object over which to iterate.440* @param {?function(this:S, T, number, ?) : boolean} f The function to call for441* for every element. This function takes 3 arguments (the element, the442* index and the array) and should return a boolean.443* @param {S=} opt_obj The object to be used as the value of 'this'444* within f.445* @return {boolean} false if any element fails the test.446* @template T,S447*/448const every = goog.NATIVE_ARRAY_PROTOTYPES &&449(ASSUME_NATIVE_FUNCTIONS || Array.prototype.every) ?450function(arr, f, opt_obj) {451asserts.assert(arr.length != null);452453return Array.prototype.every.call(arr, f, opt_obj);454} :455function(arr, f, opt_obj) {456const l = arr.length; // must be fixed during loop... see docs457const arr2 = (typeof arr === 'string') ? arr.split('') : arr;458for (let i = 0; i < l; i++) {459if (i in arr2 && !f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {460return false;461}462}463return true;464};465exports.every = every;466467468/**469* Counts the array elements that fulfill the predicate, i.e. for which the470* callback function returns true. Skips holes in the array.471*472* @param {!IArrayLike<T>|string} arr Array or array like object473* over which to iterate.474* @param {function(this: S, T, number, ?): boolean} f The function to call for475* every element. Takes 3 arguments (the element, the index and the array).476* @param {S=} opt_obj The object to be used as the value of 'this' within f.477* @return {number} The number of the matching elements.478* @template T,S479*/480function count(arr, f, opt_obj) {481let count = 0;482forEach(arr, function(element, index, arr) {483if (f.call(/** @type {?} */ (opt_obj), element, index, arr)) {484++count;485}486}, opt_obj);487return count;488}489exports.count = count;490491492/**493* Search an array for the first element that satisfies a given condition and494* return that element.495* @param {IArrayLike<T>|string} arr Array or array496* like object over which to iterate.497* @param {?function(this:S, T, number, ?) : boolean} f The function to call498* for every element. This function takes 3 arguments (the element, the499* index and the array) and should return a boolean.500* @param {S=} opt_obj An optional "this" context for the function.501* @return {T|null} The first array element that passes the test, or null if no502* element is found.503* @template T,S504*/505function find(arr, f, opt_obj) {506const i = findIndex(arr, f, opt_obj);507return i < 0 ? null : typeof arr === 'string' ? arr.charAt(i) : arr[i];508}509exports.find = find;510511512/**513* Search an array for the first element that satisfies a given condition and514* return its index.515* @param {IArrayLike<T>|string} arr Array or array516* like object over which to iterate.517* @param {?function(this:S, T, number, ?) : boolean} f The function to call for518* every element. This function519* takes 3 arguments (the element, the index and the array) and should520* return a boolean.521* @param {S=} opt_obj An optional "this" context for the function.522* @return {number} The index of the first array element that passes the test,523* or -1 if no element is found.524* @template T,S525*/526function findIndex(arr, f, opt_obj) {527const l = arr.length; // must be fixed during loop... see docs528const arr2 = (typeof arr === 'string') ? arr.split('') : arr;529for (let i = 0; i < l; i++) {530if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {531return i;532}533}534return -1;535}536exports.findIndex = findIndex;537538539/**540* Search an array (in reverse order) for the last element that satisfies a541* given condition and return that element.542* @param {IArrayLike<T>|string} arr Array or array543* like object over which to iterate.544* @param {?function(this:S, T, number, ?) : boolean} f The function to call545* for every element. This function546* takes 3 arguments (the element, the index and the array) and should547* return a boolean.548* @param {S=} opt_obj An optional "this" context for the function.549* @return {T|null} The last array element that passes the test, or null if no550* element is found.551* @template T,S552*/553function findRight(arr, f, opt_obj) {554const i = findIndexRight(arr, f, opt_obj);555return i < 0 ? null : typeof arr === 'string' ? arr.charAt(i) : arr[i];556}557exports.findRight = findRight;558559560/**561* Search an array (in reverse order) for the last element that satisfies a562* given condition and return its index.563* @param {IArrayLike<T>|string} arr Array or array564* like object over which to iterate.565* @param {?function(this:S, T, number, ?) : boolean} f The function to call566* for every element. This function567* takes 3 arguments (the element, the index and the array) and should568* return a boolean.569* @param {S=} opt_obj An optional "this" context for the function.570* @return {number} The index of the last array element that passes the test,571* or -1 if no element is found.572* @template T,S573*/574function findIndexRight(arr, f, opt_obj) {575const l = arr.length; // must be fixed during loop... see docs576const arr2 = (typeof arr === 'string') ? arr.split('') : arr;577for (let i = l - 1; i >= 0; i--) {578if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {579return i;580}581}582return -1;583}584exports.findIndexRight = findIndexRight;585586587/**588* Whether the array contains the given object.589* @param {IArrayLike<?>|string} arr The array to test for the presence of the590* element.591* @param {*} obj The object for which to test.592* @return {boolean} true if obj is present.593*/594function contains(arr, obj) {595return indexOf(arr, obj) >= 0;596}597exports.contains = contains;598599600/**601* Whether the array is empty.602* @param {IArrayLike<?>|string} arr The array to test.603* @return {boolean} true if empty.604*/605function isEmpty(arr) {606return arr.length == 0;607}608exports.isEmpty = isEmpty;609610611/**612* Clears the array.613* @param {IArrayLike<?>} arr Array or array like object to clear.614*/615function clear(arr) {616// For non real arrays we don't have the magic length so we delete the617// indices.618if (!Array.isArray(arr)) {619for (let i = arr.length - 1; i >= 0; i--) {620delete arr[i];621}622}623arr.length = 0;624}625exports.clear = clear;626627628/**629* Pushes an item into an array, if it's not already in the array.630* @param {Array<T>} arr Array into which to insert the item.631* @param {T} obj Value to add.632* @template T633*/634function insert(arr, obj) {635if (!contains(arr, obj)) {636arr.push(obj);637}638}639exports.insert = insert;640641642/**643* Inserts an object at the given index of the array.644* @param {IArrayLike<?>} arr The array to modify.645* @param {*} obj The object to insert.646* @param {number=} opt_i The index at which to insert the object. If omitted,647* treated as 0. A negative index is counted from the end of the array.648*/649function insertAt(arr, obj, opt_i) {650splice(arr, opt_i, 0, obj);651}652exports.insertAt = insertAt;653654655/**656* Inserts at the given index of the array, all elements of another array.657* @param {IArrayLike<?>} arr The array to modify.658* @param {IArrayLike<?>} elementsToAdd The array of elements to add.659* @param {number=} opt_i The index at which to insert the object. If omitted,660* treated as 0. A negative index is counted from the end of the array.661*/662function insertArrayAt(arr, elementsToAdd, opt_i) {663utils.partial(splice, arr, opt_i, 0).apply(null, elementsToAdd);664}665exports.insertArrayAt = insertArrayAt;666667668/**669* Inserts an object into an array before a specified object.670* @param {Array<T>} arr The array to modify.671* @param {T} obj The object to insert.672* @param {T=} opt_obj2 The object before which obj should be inserted. If obj2673* is omitted or not found, obj is inserted at the end of the array.674* @template T675*/676function insertBefore(arr, obj, opt_obj2) {677let i;678if (arguments.length == 2 || (i = indexOf(arr, opt_obj2)) < 0) {679arr.push(obj);680} else {681insertAt(arr, obj, i);682}683}684exports.insertBefore = insertBefore;685686687/**688* Removes the first occurrence of a particular value from an array.689* @param {IArrayLike<T>} arr Array from which to remove690* value.691* @param {T} obj Object to remove.692* @return {boolean} True if an element was removed.693* @template T694*/695function remove(arr, obj) {696const i = indexOf(arr, obj);697let rv;698if ((rv = i >= 0)) {699removeAt(arr, i);700}701return rv;702}703exports.remove = remove;704705706/**707* Removes the last occurrence of a particular value from an array.708* @param {!IArrayLike<T>} arr Array from which to remove value.709* @param {T} obj Object to remove.710* @return {boolean} True if an element was removed.711* @template T712*/713function removeLast(arr, obj) {714const i = lastIndexOf(arr, obj);715if (i >= 0) {716removeAt(arr, i);717return true;718}719return false;720}721exports.removeLast = removeLast;722723724/**725* Removes from an array the element at index i726* @param {IArrayLike<?>} arr Array or array like object from which to727* remove value.728* @param {number} i The index to remove.729* @return {boolean} True if an element was removed.730*/731function removeAt(arr, i) {732asserts.assert(arr.length != null);733734// use generic form of splice735// splice returns the removed items and if successful the length of that736// will be 1737return Array.prototype.splice.call(arr, i, 1).length == 1;738}739exports.removeAt = removeAt;740741742/**743* Removes the first value that satisfies the given condition.744* @param {IArrayLike<T>} arr Array or array745* like object over which to iterate.746* @param {?function(this:S, T, number, ?) : boolean} f The function to call747* for every element. This function748* takes 3 arguments (the element, the index and the array) and should749* return a boolean.750* @param {S=} opt_obj An optional "this" context for the function.751* @return {boolean} True if an element was removed.752* @template T,S753*/754function removeIf(arr, f, opt_obj) {755const i = findIndex(arr, f, opt_obj);756if (i >= 0) {757removeAt(arr, i);758return true;759}760return false;761}762exports.removeIf = removeIf;763764765/**766* Removes all values that satisfy the given condition.767* @param {IArrayLike<T>} arr Array or array768* like object over which to iterate.769* @param {?function(this:S, T, number, ?) : boolean} f The function to call770* for every element. This function771* takes 3 arguments (the element, the index and the array) and should772* return a boolean.773* @param {S=} opt_obj An optional "this" context for the function.774* @return {number} The number of items removed775* @template T,S776*/777function removeAllIf(arr, f, opt_obj) {778let removedCount = 0;779forEachRight(arr, function(val, index) {780if (f.call(/** @type {?} */ (opt_obj), val, index, arr)) {781if (removeAt(arr, index)) {782removedCount++;783}784}785});786return removedCount;787}788exports.removeAllIf = removeAllIf;789790791/**792* Returns a new array that is the result of joining the arguments. If arrays793* are passed then their items are added, however, if non-arrays are passed they794* will be added to the return array as is.795*796* Note that ArrayLike objects will be added as is, rather than having their797* items added.798*799* concat([1, 2], [3, 4]) -> [1, 2, 3, 4]800* concat(0, [1, 2]) -> [0, 1, 2]801* concat([1, 2], null) -> [1, 2, null]802*803* @param {...*} var_args Items to concatenate. Arrays will have each item804* added, while primitives and objects will be added as is.805* @return {!Array<?>} The new resultant array.806*/807function concat(var_args) {808return Array.prototype.concat.apply([], arguments);809}810exports.concat = concat;811812813/**814* Returns a new array that contains the contents of all the arrays passed.815* @param {...!Array<T>} var_args816* @return {!Array<T>}817* @template T818*/819function join(var_args) {820return Array.prototype.concat.apply([], arguments);821}822exports.join = join;823824825/**826* Converts an object to an array.827* @param {IArrayLike<T>|string} object The object to convert to an828* array.829* @return {!Array<T>} The object converted into an array. If object has a830* length property, every property indexed with a non-negative number831* less than length will be included in the result. If object does not832* have a length property, an empty array will be returned.833* @template T834*/835function toArray(object) {836const length = object.length;837838// If length is not a number the following is false. This case is kept for839// backwards compatibility since there are callers that pass objects that are840// not array like.841if (length > 0) {842const rv = new Array(length);843for (let i = 0; i < length; i++) {844rv[i] = object[i];845}846return rv;847}848return [];849}850exports.toArray = toArray;851852853/**854* Does a shallow copy of an array.855* @param {IArrayLike<T>|string} arr Array or array-like object to856* clone.857* @return {!Array<T>} Clone of the input array.858* @template T859*/860const clone = toArray;861exports.clone = clone;862863864/**865* Extends an array with another array, element, or "array like" object.866* This function operates 'in-place', it does not create a new Array.867*868* Example:869* var a = [];870* extend(a, [0, 1]);871* a; // [0, 1]872* extend(a, 2);873* a; // [0, 1, 2]874*875* @param {Array<VALUE>} arr1 The array to modify.876* @param {...(IArrayLike<VALUE>|VALUE)} var_args The elements or arrays of877* elements to add to arr1.878* @template VALUE879*/880function extend(arr1, var_args) {881for (let i = 1; i < arguments.length; i++) {882const arr2 = arguments[i];883if (utils.isArrayLike(arr2)) {884const len1 = arr1.length || 0;885const len2 = arr2.length || 0;886arr1.length = len1 + len2;887for (let j = 0; j < len2; j++) {888arr1[len1 + j] = arr2[j];889}890} else {891arr1.push(arr2);892}893}894}895exports.extend = extend;896897898/**899* Adds or removes elements from an array. This is a generic version of Array900* splice. This means that it might work on other objects similar to arrays,901* such as the arguments object.902*903* @param {IArrayLike<T>} arr The array to modify.904* @param {number|undefined} index The index at which to start changing the905* array. If not defined, treated as 0.906* @param {number} howMany How many elements to remove (0 means no removal. A907* value below 0 is treated as zero and so is any other non number. Numbers908* are floored).909* @param {...T} var_args Optional, additional elements to insert into the910* array.911* @return {!Array<T>} the removed elements.912* @template T913*/914function splice(arr, index, howMany, var_args) {915asserts.assert(arr.length != null);916917return Array.prototype.splice.apply(arr, slice(arguments, 1));918}919exports.splice = splice;920921922/**923* Returns a new array from a segment of an array. This is a generic version of924* Array slice. This means that it might work on other objects similar to925* arrays, such as the arguments object.926*927* @param {IArrayLike<T>|string} arr The array from928* which to copy a segment.929* @param {number} start The index of the first element to copy.930* @param {number=} opt_end The index after the last element to copy.931* @return {!Array<T>} A new array containing the specified segment of the932* original array.933* @template T934*/935function slice(arr, start, opt_end) {936asserts.assert(arr.length != null);937938// passing 1 arg to slice is not the same as passing 2 where the second is939// null or undefined (in that case the second argument is treated as 0).940// we could use slice on the arguments object and then use apply instead of941// testing the length942if (arguments.length <= 2) {943return Array.prototype.slice.call(arr, start);944} else {945return Array.prototype.slice.call(arr, start, opt_end);946}947}948exports.slice = slice;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 {IArrayLike<T>} 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*/975function removeDuplicates(arr, opt_rv, opt_hashFn) {976const returnArray = opt_rv || arr;977const defaultHashFn = function(item) {978// Prefix each type with a single character representing the type to979// prevent conflicting keys (e.g. true and 'true').980return utils.isObject(item) ? 'o' + utils.getUid(item) :981(typeof item).charAt(0) + item;982};983const hashFn = opt_hashFn || defaultHashFn;984985let cursorInsert = 0;986let cursorRead = 0;987const seen = {};988989while (cursorRead < arr.length) {990const current = arr[cursorRead++];991const key = hashFn(current);992if (!Object.prototype.hasOwnProperty.call(seen, key)) {993seen[key] = true;994returnArray[cursorInsert++] = current;995}996}997returnArray.length = cursorInsert;998}999exports.removeDuplicates = removeDuplicates;100010011002/**1003* Searches the specified array for the specified target using the binary1004* search algorithm. If no opt_compareFn is specified, elements are compared1005* using <code>defaultCompare</code>, which compares the elements1006* using the built in < and > operators. This will produce the expected1007* behavior for homogeneous arrays of String(s) and Number(s). The array1008* specified <b>must</b> be sorted in ascending order (as defined by the1009* comparison function). If the array is not sorted, results are undefined.1010* If the array contains multiple instances of the specified target value, the1011* left-most instance will be found.1012*1013* Runtime: O(log n)1014*1015* @param {IArrayLike<VALUE>} arr The array to be searched.1016* @param {TARGET} target The sought value.1017* @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison1018* function by which the array is ordered. Should take 2 arguments to1019* compare, the target value and an element from your array, and return a1020* negative number, zero, or a positive number depending on whether the1021* first argument is less than, equal to, or greater than the second.1022* @return {number} Lowest index of the target value if found, otherwise1023* (-(insertion point) - 1). The insertion point is where the value should1024* be inserted into arr to preserve the sorted property. Return value >= 01025* iff target is found.1026* @template TARGET, VALUE1027*/1028function binarySearch(arr, target, opt_compareFn) {1029return binarySearch_(1030arr, opt_compareFn || defaultCompare, false /* isEvaluator */, target);1031}1032exports.binarySearch = binarySearch;103310341035/**1036* Selects an index in the specified array using the binary search algorithm.1037* The evaluator receives an element and determines whether the desired index1038* is before, at, or after it. The evaluator must be consistent (formally,1039* map(map(arr, evaluator, opt_obj), goog.math.sign)1040* must be monotonically non-increasing).1041*1042* Runtime: O(log n)1043*1044* @param {IArrayLike<VALUE>} arr The array to be searched.1045* @param {function(this:THIS, VALUE, number, ?): number} evaluator1046* Evaluator function that receives 3 arguments (the element, the index and1047* the array). Should return a negative number, zero, or a positive number1048* depending on whether the desired index is before, at, or after the1049* element passed to it.1050* @param {THIS=} opt_obj The object to be used as the value of 'this'1051* within evaluator.1052* @return {number} Index of the leftmost element matched by the evaluator, if1053* such exists; otherwise (-(insertion point) - 1). The insertion point is1054* the index of the first element for which the evaluator returns negative,1055* or arr.length if no such element exists. The return value is non-negative1056* iff a match is found.1057* @template THIS, VALUE1058*/1059function binarySelect(arr, evaluator, opt_obj) {1060return binarySearch_(1061arr, evaluator, true /* isEvaluator */, undefined /* opt_target */,1062opt_obj);1063}1064exports.binarySelect = binarySelect;106510661067/**1068* Implementation of a binary search algorithm which knows how to use both1069* comparison functions and evaluators. If an evaluator is provided, will call1070* the evaluator with the given optional data object, conforming to the1071* interface defined in binarySelect. Otherwise, if a comparison function is1072* provided, will call the comparison function against the given data object.1073*1074* This implementation purposefully does not use goog.bind or goog.partial for1075* performance reasons.1076*1077* Runtime: O(log n)1078*1079* @param {IArrayLike<?>} arr The array to be searched.1080* @param {function(?, ?, ?): number | function(?, ?): number} compareFn1081* Either an evaluator or a comparison function, as defined by binarySearch1082* and binarySelect above.1083* @param {boolean} isEvaluator Whether the function is an evaluator or a1084* comparison function.1085* @param {?=} opt_target If the function is a comparison function, then1086* this is the target to binary search for.1087* @param {Object=} opt_selfObj If the function is an evaluator, this is an1088* optional this object for the evaluator.1089* @return {number} Lowest index of the target value if found, otherwise1090* (-(insertion point) - 1). The insertion point is where the value should1091* be inserted into arr to preserve the sorted property. Return value >= 01092* iff target is found.1093* @private1094*/1095function binarySearch_(arr, compareFn, isEvaluator, opt_target, opt_selfObj) {1096let left = 0; // inclusive1097let right = arr.length; // exclusive1098let found;1099while (left < right) {1100const middle = left + ((right - left) >>> 1);1101let compareResult;1102if (isEvaluator) {1103compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);1104} else {1105// NOTE(dimvar): To avoid this cast, we'd have to use function overloading1106// for the type of binarySearch_, which the type system can't express yet.1107compareResult = /** @type {function(?, ?): number} */ (compareFn)(1108opt_target, arr[middle]);1109}1110if (compareResult > 0) {1111left = middle + 1;1112} else {1113right = middle;1114// We are looking for the lowest index so we can't return immediately.1115found = !compareResult;1116}1117}1118// left is the index if found, or the insertion point otherwise.1119// Avoiding bitwise not operator, as that causes a loss in precision for array1120// indexes outside the bounds of a 32-bit signed integer. Array indexes have1121// a maximum value of 2^32-2 https://tc39.es/ecma262/#array-index1122return found ? left : -left - 1;1123}112411251126/**1127* Sorts the specified array into ascending order. If no opt_compareFn is1128* specified, elements are compared using1129* <code>defaultCompare</code>, which compares the elements using1130* the built in < and > operators. This will produce the expected behavior1131* for homogeneous arrays of String(s) and Number(s), unlike the native sort,1132* but will give unpredictable results for heterogeneous lists of strings and1133* numbers with different numbers of digits.1134*1135* This sort is not guaranteed to be stable.1136*1137* Runtime: Same as `Array.prototype.sort`1138*1139* @param {Array<T>} arr The array to be sorted.1140* @param {?function(T,T):number=} opt_compareFn Optional comparison1141* function by which the1142* array is to be ordered. Should take 2 arguments to compare, and return a1143* negative number, zero, or a positive number depending on whether the1144* first argument is less than, equal to, or greater than the second.1145* @template T1146*/1147function sort(arr, opt_compareFn) {1148// TODO(arv): Update type annotation since null is not accepted.1149arr.sort(opt_compareFn || defaultCompare);1150}1151exports.sort = sort;115211531154/**1155* Sorts the specified array into ascending order in a stable way. If no1156* opt_compareFn is specified, elements are compared using1157* <code>defaultCompare</code>, which compares the elements using1158* the built in < and > operators. This will produce the expected behavior1159* for homogeneous arrays of String(s) and Number(s).1160*1161* Runtime: Same as `Array.prototype.sort`, plus an additional1162* O(n) overhead of copying the array twice.1163*1164* @param {Array<T>} arr The array to be sorted.1165* @param {?function(T, T): number=} opt_compareFn Optional comparison function1166* by which the array is to be ordered. Should take 2 arguments to compare,1167* and return a negative number, zero, or a positive number depending on1168* whether the first argument is less than, equal to, or greater than the1169* second.1170* @template T1171*/1172function stableSort(arr, opt_compareFn) {1173const compArr = new Array(arr.length);1174for (let i = 0; i < arr.length; i++) {1175compArr[i] = {index: i, value: arr[i]};1176}1177const valueCompareFn = opt_compareFn || defaultCompare;1178function stableCompareFn(obj1, obj2) {1179return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;1180}1181sort(compArr, stableCompareFn);1182for (let i = 0; i < arr.length; i++) {1183arr[i] = compArr[i].value;1184}1185}1186exports.stableSort = stableSort;118711881189/**1190* Sort the specified array into ascending order based on item keys1191* returned by the specified key function.1192* If no opt_compareFn is specified, the keys are compared in ascending order1193* using <code>defaultCompare</code>.1194*1195* Runtime: O(S(f(n)), where S is runtime of <code>sort</code>1196* and f(n) is runtime of the key function.1197*1198* @param {Array<T>} arr The array to be sorted.1199* @param {function(T): K} keyFn Function taking array element and returning1200* a key used for sorting this element.1201* @param {?function(K, K): number=} opt_compareFn Optional comparison function1202* by which the keys are to be ordered. Should take 2 arguments to compare,1203* and return a negative number, zero, or a positive number depending on1204* whether the first argument is less than, equal to, or greater than the1205* second.1206* @template T,K1207*/1208function sortByKey(arr, keyFn, opt_compareFn) {1209const keyCompareFn = opt_compareFn || defaultCompare;1210sort(arr, function(a, b) {1211return keyCompareFn(keyFn(a), keyFn(b));1212});1213}1214exports.sortByKey = sortByKey;121512161217/**1218* Sorts an array of objects by the specified object key and compare1219* function. If no compare function is provided, the key values are1220* compared in ascending order using <code>defaultCompare</code>.1221* This won't work for keys that get renamed by the compiler. So use1222* {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.1223* @param {Array<Object>} arr An array of objects to sort.1224* @param {string} key The object key to sort by.1225* @param {Function=} opt_compareFn The function to use to compare key1226* values.1227*/1228function sortObjectsByKey(arr, key, opt_compareFn) {1229sortByKey(arr, function(obj) {1230return obj[key];1231}, opt_compareFn);1232}1233exports.sortObjectsByKey = sortObjectsByKey;123412351236/**1237* Tells if the array is sorted.1238* @param {!IArrayLike<T>} arr The array.1239* @param {?function(T,T):number=} opt_compareFn Function to compare the1240* array elements.1241* Should take 2 arguments to compare, and return a negative number, zero,1242* or a positive number depending on whether the first argument is less1243* than, equal to, or greater than the second.1244* @param {boolean=} opt_strict If true no equal elements are allowed.1245* @return {boolean} Whether the array is sorted.1246* @template T1247*/1248function isSorted(arr, opt_compareFn, opt_strict) {1249const compare = opt_compareFn || defaultCompare;1250for (let i = 1; i < arr.length; i++) {1251const compareResult = compare(arr[i - 1], arr[i]);1252if (compareResult > 0 || compareResult == 0 && opt_strict) {1253return false;1254}1255}1256return true;1257}1258exports.isSorted = isSorted;125912601261/**1262* Compares two arrays for equality. Two arrays are considered equal if they1263* have the same length and their corresponding elements are equal according to1264* the comparison function.1265*1266* @param {IArrayLike<A>} arr1 The first array to compare.1267* @param {IArrayLike<B>} arr2 The second array to compare.1268* @param {?function(A,B):boolean=} opt_equalsFn Optional comparison function.1269* Should take 2 arguments to compare, and return true if the arguments1270* are equal. Defaults to {@link goog.array.defaultCompareEquality} which1271* compares the elements using the built-in '===' operator.1272* @return {boolean} Whether the two arrays are equal.1273* @template A1274* @template B1275*/1276function equals(arr1, arr2, opt_equalsFn) {1277if (!utils.isArrayLike(arr1) || !utils.isArrayLike(arr2) ||1278arr1.length != arr2.length) {1279return false;1280}1281const l = arr1.length;1282const equalsFn = opt_equalsFn || defaultCompareEquality;1283for (let i = 0; i < l; i++) {1284if (!equalsFn(arr1[i], arr2[i])) {1285return false;1286}1287}1288return true;1289}1290exports.equals = equals;129112921293/**1294* 3-way array compare function.1295* @param {!IArrayLike<VALUE>} arr1 The first array to1296* compare.1297* @param {!IArrayLike<VALUE>} arr2 The second array to1298* compare.1299* @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison1300* function by which the array is to be ordered. Should take 2 arguments to1301* compare, and return a negative number, zero, or a positive number1302* depending on whether the first argument is less than, equal to, or1303* greater than the second.1304* @return {number} Negative number, zero, or a positive number depending on1305* whether the first argument is less than, equal to, or greater than the1306* second.1307* @template VALUE1308*/1309function compare3(arr1, arr2, opt_compareFn) {1310const compare = opt_compareFn || defaultCompare;1311const l = Math.min(arr1.length, arr2.length);1312for (let i = 0; i < l; i++) {1313const result = compare(arr1[i], arr2[i]);1314if (result != 0) {1315return result;1316}1317}1318return defaultCompare(arr1.length, arr2.length);1319}1320exports.compare3 = compare3;132113221323/**1324* Compares its two arguments for order, using the built in < and >1325* operators.1326* @param {VALUE} a The first object to be compared.1327* @param {VALUE} b The second object to be compared.1328* @return {number} A negative number, zero, or a positive number as the first1329* argument is less than, equal to, or greater than the second,1330* respectively.1331* @template VALUE1332*/1333function defaultCompare(a, b) {1334return a > b ? 1 : a < b ? -1 : 0;1335}1336exports.defaultCompare = defaultCompare;133713381339/**1340* Compares its two arguments for inverse order, using the built in < and >1341* operators.1342* @param {VALUE} a The first object to be compared.1343* @param {VALUE} b The second object to be compared.1344* @return {number} A negative number, zero, or a positive number as the first1345* argument is greater than, equal to, or less than the second,1346* respectively.1347* @template VALUE1348*/1349function inverseDefaultCompare(a, b) {1350return -defaultCompare(a, b);1351}1352exports.inverseDefaultCompare = inverseDefaultCompare;135313541355/**1356* Compares its two arguments for equality, using the built in === operator.1357* @param {*} a The first object to compare.1358* @param {*} b The second object to compare.1359* @return {boolean} True if the two arguments are equal, false otherwise.1360*/1361function defaultCompareEquality(a, b) {1362return a === b;1363}1364exports.defaultCompareEquality = defaultCompareEquality;136513661367/**1368* Inserts a value into a sorted array. The array is not modified if the1369* value is already present.1370* @param {IArrayLike<VALUE>} array The array to modify.1371* @param {VALUE} value The object to insert.1372* @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison1373* function by which the array is ordered. Should take 2 arguments to1374* compare, and return a negative number, zero, or a positive number1375* depending on whether the first argument is less than, equal to, or1376* greater than the second.1377* @return {boolean} True if an element was inserted.1378* @template VALUE1379*/1380function binaryInsert(array, value, opt_compareFn) {1381const index = binarySearch(array, value, opt_compareFn);1382if (index < 0) {1383insertAt(array, value, -(index + 1));1384return true;1385}1386return false;1387}1388exports.binaryInsert = binaryInsert;138913901391/**1392* Removes a value from a sorted array.1393* @param {!IArrayLike<VALUE>} array The array to modify.1394* @param {VALUE} value The object to remove.1395* @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison1396* function by which the array is ordered. Should take 2 arguments to1397* compare, and return a negative number, zero, or a positive number1398* depending on whether the first argument is less than, equal to, or1399* greater than the second.1400* @return {boolean} True if an element was removed.1401* @template VALUE1402*/1403function binaryRemove(array, value, opt_compareFn) {1404const index = binarySearch(array, value, opt_compareFn);1405return (index >= 0) ? removeAt(array, index) : false;1406}1407exports.binaryRemove = binaryRemove;140814091410/**1411* Splits an array into disjoint buckets according to a splitting function.1412* @param {IArrayLike<T>} array The array.1413* @param {function(this:S, T, number, !IArrayLike<T>):?} sorter Function to1414* call for every element. This takes 3 arguments (the element, the index1415* and the array) and must return a valid object key (a string, number,1416* etc), or undefined, if that object should not be placed in a bucket.1417* @param {S=} opt_obj The object to be used as the value of 'this' within1418* sorter.1419* @return {!Object<!Array<T>>} An object, with keys being all of the unique1420* return values of sorter, and values being arrays containing the items for1421* which the splitter returned that key.1422* @template T,S1423*/1424function bucket(array, sorter, opt_obj) {1425const buckets = {};14261427for (let i = 0; i < array.length; i++) {1428const value = array[i];1429const key = sorter.call(/** @type {?} */ (opt_obj), value, i, array);1430if (key !== undefined) {1431// Push the value to the right bucket, creating it if necessary.1432const bucket = buckets[key] || (buckets[key] = []);1433bucket.push(value);1434}1435}14361437return buckets;1438}1439exports.bucket = bucket;144014411442/**1443* Splits an array into disjoint buckets according to a splitting function.1444* @param {!IArrayLike<V>} array The array.1445* @param {function(V, number, !IArrayLike<V>):(K|undefined)} sorter Function to1446* call for every element. This takes 3 arguments (the element, the index,1447* and the array) and must return a value to use as a key, or undefined, if1448* that object should not be placed in a bucket.1449* @return {!Map<K, !Array<V>>} A map, with keys being all of the unique1450* return values of sorter, and values being arrays containing the items for1451* which the splitter returned that key.1452* @template K,V1453*/1454function bucketToMap(array, sorter) {1455const /** !Map<K, !Array<V>> */ buckets = new Map();14561457for (let i = 0; i < array.length; i++) {1458const value = array[i];1459const key = sorter(value, i, array);1460if (key !== undefined) {1461// Push the value to the right bucket, creating it if necessary.1462let bucket = buckets.get(key);1463if (!bucket) {1464bucket = [];1465buckets.set(key, bucket);1466}1467bucket.push(value);1468}1469}14701471return buckets;1472}1473exports.bucketToMap = bucketToMap;147414751476/**1477* Creates a new object built from the provided array and the key-generation1478* function.1479* @param {IArrayLike<T>} arr Array or array like object over1480* which to iterate whose elements will be the values in the new object.1481* @param {?function(this:S, T, number, ?) : string} keyFunc The function to1482* call for every element. This function takes 3 arguments (the element, the1483* index and the array) and should return a string that will be used as the1484* key for the element in the new object. If the function returns the same1485* key for more than one element, the value for that key is1486* implementation-defined.1487* @param {S=} opt_obj The object to be used as the value of 'this'1488* within keyFunc.1489* @return {!Object<T>} The new object.1490* @template T,S1491*/1492function toObject(arr, keyFunc, opt_obj) {1493const ret = {};1494forEach(arr, function(element, index) {1495ret[keyFunc.call(/** @type {?} */ (opt_obj), element, index, arr)] =1496element;1497});1498return ret;1499}1500exports.toObject = toObject;150115021503/**1504* Creates a new ES6 Map built from the provided array and the key-generation1505* function.1506* @param {!IArrayLike<V>} arr Array or array like object over which to iterate1507* whose elements will be the values in the new object.1508* @param {?function(V, number, ?) : K} keyFunc The function to call for every1509* element. This function takes 3 arguments (the element, the index, and the1510* array) and should return a value that will be used as the key for the1511* element in the new object. If the function returns the same key for more1512* than one element, the value for that key is implementation-defined.1513* @return {!Map<K, V>} The new map.1514* @template K,V1515*/1516function toMap(arr, keyFunc) {1517const /** !Map<K, V> */ map = new Map();15181519for (let i = 0; i < arr.length; i++) {1520const element = arr[i];1521map.set(keyFunc(element, i, arr), element);1522}15231524return map;1525}1526exports.toMap = toMap;152715281529/**1530* Creates a range of numbers in an arithmetic progression.1531*1532* Range takes 1, 2, or 3 arguments:1533* <pre>1534* range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]1535* range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]1536* range(-2, -5, -1) produces [-2, -3, -4]1537* range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.1538* </pre>1539*1540* @param {number} startOrEnd The starting value of the range if an end argument1541* is provided. Otherwise, the start value is 0, and this is the end value.1542* @param {number=} opt_end The optional end value of the range.1543* @param {number=} opt_step The step size between range values. Defaults to 11544* if opt_step is undefined or 0.1545* @return {!Array<number>} An array of numbers for the requested range. May be1546* an empty array if adding the step would not converge toward the end1547* value.1548*/1549function range(startOrEnd, opt_end, opt_step) {1550const array = [];1551let start = 0;1552let end = startOrEnd;1553const step = opt_step || 1;1554if (opt_end !== undefined) {1555start = startOrEnd;1556end = opt_end;1557}15581559if (step * (end - start) < 0) {1560// Sign mismatch: start + step will never reach the end value.1561return [];1562}15631564if (step > 0) {1565for (let i = start; i < end; i += step) {1566array.push(i);1567}1568} else {1569for (let i = start; i > end; i += step) {1570array.push(i);1571}1572}1573return array;1574}1575exports.range = range;157615771578/**1579* Returns an array consisting of the given value repeated N times.1580*1581* @param {VALUE} value The value to repeat.1582* @param {number} n The repeat count.1583* @return {!Array<VALUE>} An array with the repeated value.1584* @template VALUE1585*/1586function repeat(value, n) {1587const array = [];1588for (let i = 0; i < n; i++) {1589array[i] = value;1590}1591return array;1592}1593exports.repeat = repeat;159415951596/**1597* Returns an array consisting of every argument with all arrays1598* expanded in-place recursively.1599*1600* @param {...*} var_args The values to flatten.1601* @return {!Array<?>} An array containing the flattened values.1602*/1603function flatten(var_args) {1604const CHUNK_SIZE = 8192;16051606const result = [];1607for (let i = 0; i < arguments.length; i++) {1608const element = arguments[i];1609if (Array.isArray(element)) {1610for (let c = 0; c < element.length; c += CHUNK_SIZE) {1611const chunk = slice(element, c, c + CHUNK_SIZE);1612const recurseResult = flatten.apply(null, chunk);1613for (let r = 0; r < recurseResult.length; r++) {1614result.push(recurseResult[r]);1615}1616}1617} else {1618result.push(element);1619}1620}1621return result;1622}1623exports.flatten = flatten;162416251626/**1627* Rotates an array in-place. After calling this method, the element at1628* index i will be the element previously at index (i - n) %1629* array.length, for all values of i between 0 and array.length - 1,1630* inclusive.1631*1632* For example, suppose list comprises [t, a, n, k, s]. After invoking1633* rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].1634*1635* @param {!Array<T>} array The array to rotate.1636* @param {number} n The amount to rotate.1637* @return {!Array<T>} The array.1638* @template T1639*/1640function rotate(array, n) {1641asserts.assert(array.length != null);16421643if (array.length) {1644n %= array.length;1645if (n > 0) {1646Array.prototype.unshift.apply(array, array.splice(-n, n));1647} else if (n < 0) {1648Array.prototype.push.apply(array, array.splice(0, -n));1649}1650}1651return array;1652}1653exports.rotate = rotate;165416551656/**1657* Moves one item of an array to a new position keeping the order of the rest1658* of the items. Example use case: keeping a list of JavaScript objects1659* synchronized with the corresponding list of DOM elements after one of the1660* elements has been dragged to a new position.1661* @param {!IArrayLike<?>} arr The array to modify.1662* @param {number} fromIndex Index of the item to move between 0 and1663* `arr.length - 1`.1664* @param {number} toIndex Target index between 0 and `arr.length - 1`.1665*/1666function moveItem(arr, fromIndex, toIndex) {1667asserts.assert(fromIndex >= 0 && fromIndex < arr.length);1668asserts.assert(toIndex >= 0 && toIndex < arr.length);1669// Remove 1 item at fromIndex.1670const removedItems = Array.prototype.splice.call(arr, fromIndex, 1);1671// Insert the removed item at toIndex.1672Array.prototype.splice.call(arr, toIndex, 0, removedItems[0]);1673// We don't use goog.array.insertAt and goog.array.removeAt, because they're1674// significantly slower than splice.1675}1676exports.moveItem = moveItem;167716781679/**1680* Creates a new array for which the element at position i is an array of the1681* ith element of the provided arrays. The returned array will only be as long1682* as the shortest array provided; additional values are ignored. For example,1683* the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].1684*1685* This is similar to the zip() function in Python. See {@link1686* http://docs.python.org/library/functions.html#zip}1687*1688* @param {...!IArrayLike<?>} var_args Arrays to be combined.1689* @return {!Array<!Array<?>>} A new array of arrays created from1690* provided arrays.1691*/1692function zip(var_args) {1693if (!arguments.length) {1694return [];1695}1696const result = [];1697let minLen = arguments[0].length;1698for (let i = 1; i < arguments.length; i++) {1699if (arguments[i].length < minLen) {1700minLen = arguments[i].length;1701}1702}1703for (let i = 0; i < minLen; i++) {1704const value = [];1705for (let j = 0; j < arguments.length; j++) {1706value.push(arguments[j][i]);1707}1708result.push(value);1709}1710return result;1711}1712exports.zip = zip;171317141715/**1716* Shuffles the values in the specified array using the Fisher-Yates in-place1717* shuffle (also known as the Knuth Shuffle). By default, calls Math.random()1718* and so resets the state of that random number generator. Similarly, may reset1719* the state of any other specified random number generator.1720*1721* Runtime: O(n)1722*1723* @param {!Array<?>} arr The array to be shuffled.1724* @param {function():number=} opt_randFn Optional random function to use for1725* shuffling.1726* Takes no arguments, and returns a random number on the interval [0, 1).1727* Defaults to Math.random() using JavaScript's built-in Math library.1728*/1729function shuffle(arr, opt_randFn) {1730const randFn = opt_randFn || Math.random;17311732for (let i = arr.length - 1; i > 0; i--) {1733// Choose a random array index in [0, i] (inclusive with i).1734const j = Math.floor(randFn() * (i + 1));17351736const tmp = arr[i];1737arr[i] = arr[j];1738arr[j] = tmp;1739}1740}1741exports.shuffle = shuffle;174217431744/**1745* Returns a new array of elements from arr, based on the indexes of elements1746* provided by index_arr. For example, the result of index copying1747* ['a', 'b', 'c'] with index_arr [1,0,0,2] is ['b', 'a', 'a', 'c'].1748*1749* @param {!IArrayLike<T>} arr The array to get a indexed copy from.1750* @param {!IArrayLike<number>} index_arr An array of indexes to get from arr.1751* @return {!Array<T>} A new array of elements from arr in index_arr order.1752* @template T1753*/1754function copyByIndex(arr, index_arr) {1755const result = [];1756forEach(index_arr, function(index) {1757result.push(arr[index]);1758});1759return result;1760}1761exports.copyByIndex = copyByIndex;176217631764/**1765* Maps each element of the input array into zero or more elements of the output1766* array.1767*1768* @param {!IArrayLike<VALUE>|string} arr Array or array like object1769* over which to iterate.1770* @param {function(this:THIS, VALUE, number, ?): !Array<RESULT>} f The function1771* to call for every element. This function takes 3 arguments (the element,1772* the index and the array) and should return an array. The result will be1773* used to extend a new array.1774* @param {THIS=} opt_obj The object to be used as the value of 'this' within f.1775* @return {!Array<RESULT>} a new array with the concatenation of all arrays1776* returned from f.1777* @template THIS, VALUE, RESULT1778*/1779function concatMap(arr, f, opt_obj) {1780return concat.apply([], map(arr, f, opt_obj));1781}1782exports.concatMap = concatMap;178317841785