123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665 |
- // Copyright 2006 The Closure Library Authors. All Rights Reserved.
- //
- // Licensed under the Apache License, Version 2.0 (the "License");
- // you may not use this file except in compliance with the License.
- // You may obtain a copy of the License at
- //
- // http://www.apache.org/licenses/LICENSE-2.0
- //
- // Unless required by applicable law or agreed to in writing, software
- // distributed under the License is distributed on an "AS-IS" BASIS,
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- // See the License for the specific language governing permissions and
- // limitations under the License.
- /**
- * @fileoverview Utilities for manipulating arrays.
- *
- * @author arv@google.com (Erik Arvidsson)
- */
- goog.provide('goog.array');
- goog.require('goog.asserts');
- /**
- * @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should
- * rely on Array.prototype functions, if available.
- *
- * The Array.prototype functions can be defined by external libraries like
- * Prototype and setting this flag to false forces closure to use its own
- * goog.array implementation.
- *
- * If your javascript can be loaded by a third party site and you are wary about
- * relying on the prototype functions, specify
- * "--define goog.NATIVE_ARRAY_PROTOTYPES=false" to the JSCompiler.
- *
- * Setting goog.TRUSTED_SITE to false will automatically set
- * NATIVE_ARRAY_PROTOTYPES to false.
- */
- goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE);
- /**
- * @define {boolean} If true, JSCompiler will use the native implementation of
- * array functions where appropriate (e.g., {@code Array#filter}) and remove the
- * unused pure JS implementation.
- */
- goog.define('goog.array.ASSUME_NATIVE_FUNCTIONS', false);
- /**
- * Returns the last element in an array without removing it.
- * Same as goog.array.last.
- * @param {IArrayLike<T>|string} array The array.
- * @return {T} Last item in array.
- * @template T
- */
- goog.array.peek = function(array) {
- return array[array.length - 1];
- };
- /**
- * Returns the last element in an array without removing it.
- * Same as goog.array.peek.
- * @param {IArrayLike<T>|string} array The array.
- * @return {T} Last item in array.
- * @template T
- */
- goog.array.last = goog.array.peek;
- // NOTE(arv): Since most of the array functions are generic it allows you to
- // pass an array-like object. Strings have a length and are considered array-
- // like. However, the 'in' operator does not work on strings so we cannot just
- // use the array path even if the browser supports indexing into strings. We
- // therefore end up splitting the string.
- /**
- * Returns the index of the first element of an array with a specified value, or
- * -1 if the element is not present in the array.
- *
- * See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}
- *
- * @param {IArrayLike<T>|string} arr The array to be searched.
- * @param {T} obj The object for which we are searching.
- * @param {number=} opt_fromIndex The index at which to start the search. If
- * omitted the search starts at index 0.
- * @return {number} The index of the first matching array element.
- * @template T
- */
- goog.array.indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&
- (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.indexOf) ?
- function(arr, obj, opt_fromIndex) {
- goog.asserts.assert(arr.length != null);
- return Array.prototype.indexOf.call(arr, obj, opt_fromIndex);
- } :
- function(arr, obj, opt_fromIndex) {
- var fromIndex = opt_fromIndex == null ?
- 0 :
- (opt_fromIndex < 0 ? Math.max(0, arr.length + opt_fromIndex) :
- opt_fromIndex);
- if (goog.isString(arr)) {
- // Array.prototype.indexOf uses === so only strings should be found.
- if (!goog.isString(obj) || obj.length != 1) {
- return -1;
- }
- return arr.indexOf(obj, fromIndex);
- }
- for (var i = fromIndex; i < arr.length; i++) {
- if (i in arr && arr[i] === obj) return i;
- }
- return -1;
- };
- /**
- * Returns the index of the last element of an array with a specified value, or
- * -1 if the element is not present in the array.
- *
- * See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof}
- *
- * @param {!IArrayLike<T>|string} arr The array to be searched.
- * @param {T} obj The object for which we are searching.
- * @param {?number=} opt_fromIndex The index at which to start the search. If
- * omitted the search starts at the end of the array.
- * @return {number} The index of the last matching array element.
- * @template T
- */
- goog.array.lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&
- (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.lastIndexOf) ?
- function(arr, obj, opt_fromIndex) {
- goog.asserts.assert(arr.length != null);
- // Firefox treats undefined and null as 0 in the fromIndex argument which
- // leads it to always return -1
- var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;
- return Array.prototype.lastIndexOf.call(arr, obj, fromIndex);
- } :
- function(arr, obj, opt_fromIndex) {
- var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;
- if (fromIndex < 0) {
- fromIndex = Math.max(0, arr.length + fromIndex);
- }
- if (goog.isString(arr)) {
- // Array.prototype.lastIndexOf uses === so only strings should be found.
- if (!goog.isString(obj) || obj.length != 1) {
- return -1;
- }
- return arr.lastIndexOf(obj, fromIndex);
- }
- for (var i = fromIndex; i >= 0; i--) {
- if (i in arr && arr[i] === obj) return i;
- }
- return -1;
- };
- /**
- * Calls a function for each element in an array. Skips holes in the array.
- * See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}
- *
- * @param {IArrayLike<T>|string} arr Array or array like object over
- * which to iterate.
- * @param {?function(this: S, T, number, ?): ?} f The function to call for every
- * element. This function takes 3 arguments (the element, the index and the
- * array). The return value is ignored.
- * @param {S=} opt_obj The object to be used as the value of 'this' within f.
- * @template T,S
- */
- goog.array.forEach = goog.NATIVE_ARRAY_PROTOTYPES &&
- (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.forEach) ?
- function(arr, f, opt_obj) {
- goog.asserts.assert(arr.length != null);
- Array.prototype.forEach.call(arr, f, opt_obj);
- } :
- function(arr, f, opt_obj) {
- var l = arr.length; // must be fixed during loop... see docs
- var arr2 = goog.isString(arr) ? arr.split('') : arr;
- for (var i = 0; i < l; i++) {
- if (i in arr2) {
- f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);
- }
- }
- };
- /**
- * Calls a function for each element in an array, starting from the last
- * element rather than the first.
- *
- * @param {IArrayLike<T>|string} arr Array or array
- * like object over which to iterate.
- * @param {?function(this: S, T, number, ?): ?} f The function to call for every
- * element. This function
- * takes 3 arguments (the element, the index and the array). The return
- * value is ignored.
- * @param {S=} opt_obj The object to be used as the value of 'this'
- * within f.
- * @template T,S
- */
- goog.array.forEachRight = function(arr, f, opt_obj) {
- var l = arr.length; // must be fixed during loop... see docs
- var arr2 = goog.isString(arr) ? arr.split('') : arr;
- for (var i = l - 1; i >= 0; --i) {
- if (i in arr2) {
- f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);
- }
- }
- };
- /**
- * Calls a function for each element in an array, and if the function returns
- * true adds the element to a new array.
- *
- * See {@link http://tinyurl.com/developer-mozilla-org-array-filter}
- *
- * @param {IArrayLike<T>|string} arr Array or array
- * like object over which to iterate.
- * @param {?function(this:S, T, number, ?):boolean} f The function to call for
- * every element. This function
- * takes 3 arguments (the element, the index and the array) and must
- * return a Boolean. If the return value is true the element is added to the
- * result array. If it is false the element is not included.
- * @param {S=} opt_obj The object to be used as the value of 'this'
- * within f.
- * @return {!Array<T>} a new array in which only elements that passed the test
- * are present.
- * @template T,S
- */
- goog.array.filter = goog.NATIVE_ARRAY_PROTOTYPES &&
- (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.filter) ?
- function(arr, f, opt_obj) {
- goog.asserts.assert(arr.length != null);
- return Array.prototype.filter.call(arr, f, opt_obj);
- } :
- function(arr, f, opt_obj) {
- var l = arr.length; // must be fixed during loop... see docs
- var res = [];
- var resLength = 0;
- var arr2 = goog.isString(arr) ? arr.split('') : arr;
- for (var i = 0; i < l; i++) {
- if (i in arr2) {
- var val = arr2[i]; // in case f mutates arr2
- if (f.call(/** @type {?} */ (opt_obj), val, i, arr)) {
- res[resLength++] = val;
- }
- }
- }
- return res;
- };
- /**
- * Calls a function for each element in an array and inserts the result into a
- * new array.
- *
- * See {@link http://tinyurl.com/developer-mozilla-org-array-map}
- *
- * @param {IArrayLike<VALUE>|string} arr Array or array like object
- * over which to iterate.
- * @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call
- * for every element. This function takes 3 arguments (the element,
- * the index and the array) and should return something. The result will be
- * inserted into a new array.
- * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.
- * @return {!Array<RESULT>} a new array with the results from f.
- * @template THIS, VALUE, RESULT
- */
- goog.array.map = goog.NATIVE_ARRAY_PROTOTYPES &&
- (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.map) ?
- function(arr, f, opt_obj) {
- goog.asserts.assert(arr.length != null);
- return Array.prototype.map.call(arr, f, opt_obj);
- } :
- function(arr, f, opt_obj) {
- var l = arr.length; // must be fixed during loop... see docs
- var res = new Array(l);
- var arr2 = goog.isString(arr) ? arr.split('') : arr;
- for (var i = 0; i < l; i++) {
- if (i in arr2) {
- res[i] = f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);
- }
- }
- return res;
- };
- /**
- * Passes every element of an array into a function and accumulates the result.
- *
- * See {@link http://tinyurl.com/developer-mozilla-org-array-reduce}
- *
- * For example:
- * var a = [1, 2, 3, 4];
- * goog.array.reduce(a, function(r, v, i, arr) {return r + v;}, 0);
- * returns 10
- *
- * @param {IArrayLike<T>|string} arr Array or array
- * like object over which to iterate.
- * @param {function(this:S, R, T, number, ?) : R} f The function to call for
- * every element. This function
- * takes 4 arguments (the function's previous result or the initial value,
- * the value of the current array element, the current array index, and the
- * array itself)
- * function(previousValue, currentValue, index, array).
- * @param {?} val The initial value to pass into the function on the first call.
- * @param {S=} opt_obj The object to be used as the value of 'this'
- * within f.
- * @return {R} Result of evaluating f repeatedly across the values of the array.
- * @template T,S,R
- */
- goog.array.reduce = goog.NATIVE_ARRAY_PROTOTYPES &&
- (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduce) ?
- function(arr, f, val, opt_obj) {
- goog.asserts.assert(arr.length != null);
- if (opt_obj) {
- f = goog.bind(f, opt_obj);
- }
- return Array.prototype.reduce.call(arr, f, val);
- } :
- function(arr, f, val, opt_obj) {
- var rval = val;
- goog.array.forEach(arr, function(val, index) {
- rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);
- });
- return rval;
- };
- /**
- * Passes every element of an array into a function and accumulates the result,
- * starting from the last element and working towards the first.
- *
- * See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright}
- *
- * For example:
- * var a = ['a', 'b', 'c'];
- * goog.array.reduceRight(a, function(r, v, i, arr) {return r + v;}, '');
- * returns 'cba'
- *
- * @param {IArrayLike<T>|string} arr Array or array
- * like object over which to iterate.
- * @param {?function(this:S, R, T, number, ?) : R} f The function to call for
- * every element. This function
- * takes 4 arguments (the function's previous result or the initial value,
- * the value of the current array element, the current array index, and the
- * array itself)
- * function(previousValue, currentValue, index, array).
- * @param {?} val The initial value to pass into the function on the first call.
- * @param {S=} opt_obj The object to be used as the value of 'this'
- * within f.
- * @return {R} Object returned as a result of evaluating f repeatedly across the
- * values of the array.
- * @template T,S,R
- */
- goog.array.reduceRight = goog.NATIVE_ARRAY_PROTOTYPES &&
- (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduceRight) ?
- function(arr, f, val, opt_obj) {
- goog.asserts.assert(arr.length != null);
- goog.asserts.assert(f != null);
- if (opt_obj) {
- f = goog.bind(f, opt_obj);
- }
- return Array.prototype.reduceRight.call(arr, f, val);
- } :
- function(arr, f, val, opt_obj) {
- var rval = val;
- goog.array.forEachRight(arr, function(val, index) {
- rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);
- });
- return rval;
- };
- /**
- * Calls f for each element of an array. If any call returns true, some()
- * returns true (without checking the remaining elements). If all calls
- * return false, some() returns false.
- *
- * See {@link http://tinyurl.com/developer-mozilla-org-array-some}
- *
- * @param {IArrayLike<T>|string} arr Array or array
- * like object over which to iterate.
- * @param {?function(this:S, T, number, ?) : boolean} f The function to call for
- * for every element. This function takes 3 arguments (the element, the
- * index and the array) and should return a boolean.
- * @param {S=} opt_obj The object to be used as the value of 'this'
- * within f.
- * @return {boolean} true if any element passes the test.
- * @template T,S
- */
- goog.array.some = goog.NATIVE_ARRAY_PROTOTYPES &&
- (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.some) ?
- function(arr, f, opt_obj) {
- goog.asserts.assert(arr.length != null);
- return Array.prototype.some.call(arr, f, opt_obj);
- } :
- function(arr, f, opt_obj) {
- var l = arr.length; // must be fixed during loop... see docs
- var arr2 = goog.isString(arr) ? arr.split('') : arr;
- for (var i = 0; i < l; i++) {
- if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {
- return true;
- }
- }
- return false;
- };
- /**
- * Call f for each element of an array. If all calls return true, every()
- * returns true. If any call returns false, every() returns false and
- * does not continue to check the remaining elements.
- *
- * See {@link http://tinyurl.com/developer-mozilla-org-array-every}
- *
- * @param {IArrayLike<T>|string} arr Array or array
- * like object over which to iterate.
- * @param {?function(this:S, T, number, ?) : boolean} f The function to call for
- * for every element. This function takes 3 arguments (the element, the
- * index and the array) and should return a boolean.
- * @param {S=} opt_obj The object to be used as the value of 'this'
- * within f.
- * @return {boolean} false if any element fails the test.
- * @template T,S
- */
- goog.array.every = goog.NATIVE_ARRAY_PROTOTYPES &&
- (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.every) ?
- function(arr, f, opt_obj) {
- goog.asserts.assert(arr.length != null);
- return Array.prototype.every.call(arr, f, opt_obj);
- } :
- function(arr, f, opt_obj) {
- var l = arr.length; // must be fixed during loop... see docs
- var arr2 = goog.isString(arr) ? arr.split('') : arr;
- for (var i = 0; i < l; i++) {
- if (i in arr2 && !f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {
- return false;
- }
- }
- return true;
- };
- /**
- * Counts the array elements that fulfill the predicate, i.e. for which the
- * callback function returns true. Skips holes in the array.
- *
- * @param {!IArrayLike<T>|string} arr Array or array like object
- * over which to iterate.
- * @param {function(this: S, T, number, ?): boolean} f The function to call for
- * every element. Takes 3 arguments (the element, the index and the array).
- * @param {S=} opt_obj The object to be used as the value of 'this' within f.
- * @return {number} The number of the matching elements.
- * @template T,S
- */
- goog.array.count = function(arr, f, opt_obj) {
- var count = 0;
- goog.array.forEach(arr, function(element, index, arr) {
- if (f.call(/** @type {?} */ (opt_obj), element, index, arr)) {
- ++count;
- }
- }, opt_obj);
- return count;
- };
- /**
- * Search an array for the first element that satisfies a given condition and
- * return that element.
- * @param {IArrayLike<T>|string} arr Array or array
- * like object over which to iterate.
- * @param {?function(this:S, T, number, ?) : boolean} f The function to call
- * for every element. This function takes 3 arguments (the element, the
- * index and the array) and should return a boolean.
- * @param {S=} opt_obj An optional "this" context for the function.
- * @return {T|null} The first array element that passes the test, or null if no
- * element is found.
- * @template T,S
- */
- goog.array.find = function(arr, f, opt_obj) {
- var i = goog.array.findIndex(arr, f, opt_obj);
- return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];
- };
- /**
- * Search an array for the first element that satisfies a given condition and
- * return its index.
- * @param {IArrayLike<T>|string} arr Array or array
- * like object over which to iterate.
- * @param {?function(this:S, T, number, ?) : boolean} f The function to call for
- * every element. This function
- * takes 3 arguments (the element, the index and the array) and should
- * return a boolean.
- * @param {S=} opt_obj An optional "this" context for the function.
- * @return {number} The index of the first array element that passes the test,
- * or -1 if no element is found.
- * @template T,S
- */
- goog.array.findIndex = function(arr, f, opt_obj) {
- var l = arr.length; // must be fixed during loop... see docs
- var arr2 = goog.isString(arr) ? arr.split('') : arr;
- for (var i = 0; i < l; i++) {
- if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {
- return i;
- }
- }
- return -1;
- };
- /**
- * Search an array (in reverse order) for the last element that satisfies a
- * given condition and return that element.
- * @param {IArrayLike<T>|string} arr Array or array
- * like object over which to iterate.
- * @param {?function(this:S, T, number, ?) : boolean} f The function to call
- * for every element. This function
- * takes 3 arguments (the element, the index and the array) and should
- * return a boolean.
- * @param {S=} opt_obj An optional "this" context for the function.
- * @return {T|null} The last array element that passes the test, or null if no
- * element is found.
- * @template T,S
- */
- goog.array.findRight = function(arr, f, opt_obj) {
- var i = goog.array.findIndexRight(arr, f, opt_obj);
- return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];
- };
- /**
- * Search an array (in reverse order) for the last element that satisfies a
- * given condition and return its index.
- * @param {IArrayLike<T>|string} arr Array or array
- * like object over which to iterate.
- * @param {?function(this:S, T, number, ?) : boolean} f The function to call
- * for every element. This function
- * takes 3 arguments (the element, the index and the array) and should
- * return a boolean.
- * @param {S=} opt_obj An optional "this" context for the function.
- * @return {number} The index of the last array element that passes the test,
- * or -1 if no element is found.
- * @template T,S
- */
- goog.array.findIndexRight = function(arr, f, opt_obj) {
- var l = arr.length; // must be fixed during loop... see docs
- var arr2 = goog.isString(arr) ? arr.split('') : arr;
- for (var i = l - 1; i >= 0; i--) {
- if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {
- return i;
- }
- }
- return -1;
- };
- /**
- * Whether the array contains the given object.
- * @param {IArrayLike<?>|string} arr The array to test for the presence of the
- * element.
- * @param {*} obj The object for which to test.
- * @return {boolean} true if obj is present.
- */
- goog.array.contains = function(arr, obj) {
- return goog.array.indexOf(arr, obj) >= 0;
- };
- /**
- * Whether the array is empty.
- * @param {IArrayLike<?>|string} arr The array to test.
- * @return {boolean} true if empty.
- */
- goog.array.isEmpty = function(arr) {
- return arr.length == 0;
- };
- /**
- * Clears the array.
- * @param {IArrayLike<?>} arr Array or array like object to clear.
- */
- goog.array.clear = function(arr) {
- // For non real arrays we don't have the magic length so we delete the
- // indices.
- if (!goog.isArray(arr)) {
- for (var i = arr.length - 1; i >= 0; i--) {
- delete arr[i];
- }
- }
- arr.length = 0;
- };
- /**
- * Pushes an item into an array, if it's not already in the array.
- * @param {Array<T>} arr Array into which to insert the item.
- * @param {T} obj Value to add.
- * @template T
- */
- goog.array.insert = function(arr, obj) {
- if (!goog.array.contains(arr, obj)) {
- arr.push(obj);
- }
- };
- /**
- * Inserts an object at the given index of the array.
- * @param {IArrayLike<?>} arr The array to modify.
- * @param {*} obj The object to insert.
- * @param {number=} opt_i The index at which to insert the object. If omitted,
- * treated as 0. A negative index is counted from the end of the array.
- */
- goog.array.insertAt = function(arr, obj, opt_i) {
- goog.array.splice(arr, opt_i, 0, obj);
- };
- /**
- * Inserts at the given index of the array, all elements of another array.
- * @param {IArrayLike<?>} arr The array to modify.
- * @param {IArrayLike<?>} elementsToAdd The array of elements to add.
- * @param {number=} opt_i The index at which to insert the object. If omitted,
- * treated as 0. A negative index is counted from the end of the array.
- */
- goog.array.insertArrayAt = function(arr, elementsToAdd, opt_i) {
- goog.partial(goog.array.splice, arr, opt_i, 0).apply(null, elementsToAdd);
- };
- /**
- * Inserts an object into an array before a specified object.
- * @param {Array<T>} arr The array to modify.
- * @param {T} obj The object to insert.
- * @param {T=} opt_obj2 The object before which obj should be inserted. If obj2
- * is omitted or not found, obj is inserted at the end of the array.
- * @template T
- */
- goog.array.insertBefore = function(arr, obj, opt_obj2) {
- var i;
- if (arguments.length == 2 || (i = goog.array.indexOf(arr, opt_obj2)) < 0) {
- arr.push(obj);
- } else {
- goog.array.insertAt(arr, obj, i);
- }
- };
- /**
- * Removes the first occurrence of a particular value from an array.
- * @param {IArrayLike<T>} arr Array from which to remove
- * value.
- * @param {T} obj Object to remove.
- * @return {boolean} True if an element was removed.
- * @template T
- */
- goog.array.remove = function(arr, obj) {
- var i = goog.array.indexOf(arr, obj);
- var rv;
- if ((rv = i >= 0)) {
- goog.array.removeAt(arr, i);
- }
- return rv;
- };
- /**
- * Removes the last occurrence of a particular value from an array.
- * @param {!IArrayLike<T>} arr Array from which to remove value.
- * @param {T} obj Object to remove.
- * @return {boolean} True if an element was removed.
- * @template T
- */
- goog.array.removeLast = function(arr, obj) {
- var i = goog.array.lastIndexOf(arr, obj);
- if (i >= 0) {
- goog.array.removeAt(arr, i);
- return true;
- }
- return false;
- };
- /**
- * Removes from an array the element at index i
- * @param {IArrayLike<?>} arr Array or array like object from which to
- * remove value.
- * @param {number} i The index to remove.
- * @return {boolean} True if an element was removed.
- */
- goog.array.removeAt = function(arr, i) {
- goog.asserts.assert(arr.length != null);
- // use generic form of splice
- // splice returns the removed items and if successful the length of that
- // will be 1
- return Array.prototype.splice.call(arr, i, 1).length == 1;
- };
- /**
- * Removes the first value that satisfies the given condition.
- * @param {IArrayLike<T>} arr Array or array
- * like object over which to iterate.
- * @param {?function(this:S, T, number, ?) : boolean} f The function to call
- * for every element. This function
- * takes 3 arguments (the element, the index and the array) and should
- * return a boolean.
- * @param {S=} opt_obj An optional "this" context for the function.
- * @return {boolean} True if an element was removed.
- * @template T,S
- */
- goog.array.removeIf = function(arr, f, opt_obj) {
- var i = goog.array.findIndex(arr, f, opt_obj);
- if (i >= 0) {
- goog.array.removeAt(arr, i);
- return true;
- }
- return false;
- };
- /**
- * Removes all values that satisfy the given condition.
- * @param {IArrayLike<T>} arr Array or array
- * like object over which to iterate.
- * @param {?function(this:S, T, number, ?) : boolean} f The function to call
- * for every element. This function
- * takes 3 arguments (the element, the index and the array) and should
- * return a boolean.
- * @param {S=} opt_obj An optional "this" context for the function.
- * @return {number} The number of items removed
- * @template T,S
- */
- goog.array.removeAllIf = function(arr, f, opt_obj) {
- var removedCount = 0;
- goog.array.forEachRight(arr, function(val, index) {
- if (f.call(/** @type {?} */ (opt_obj), val, index, arr)) {
- if (goog.array.removeAt(arr, index)) {
- removedCount++;
- }
- }
- });
- return removedCount;
- };
- /**
- * Returns a new array that is the result of joining the arguments. If arrays
- * are passed then their items are added, however, if non-arrays are passed they
- * will be added to the return array as is.
- *
- * Note that ArrayLike objects will be added as is, rather than having their
- * items added.
- *
- * goog.array.concat([1, 2], [3, 4]) -> [1, 2, 3, 4]
- * goog.array.concat(0, [1, 2]) -> [0, 1, 2]
- * goog.array.concat([1, 2], null) -> [1, 2, null]
- *
- * There is bug in all current versions of IE (6, 7 and 8) where arrays created
- * in an iframe become corrupted soon (not immediately) after the iframe is
- * destroyed. This is common if loading data via goog.net.IframeIo, for example.
- * This corruption only affects the concat method which will start throwing
- * Catastrophic Errors (#-2147418113).
- *
- * See http://endoflow.com/scratch/corrupted-arrays.html for a test case.
- *
- * Internally goog.array should use this, so that all methods will continue to
- * work on these broken array objects.
- *
- * @param {...*} var_args Items to concatenate. Arrays will have each item
- * added, while primitives and objects will be added as is.
- * @return {!Array<?>} The new resultant array.
- */
- goog.array.concat = function(var_args) {
- return Array.prototype.concat.apply([], arguments);
- };
- /**
- * Returns a new array that contains the contents of all the arrays passed.
- * @param {...!Array<T>} var_args
- * @return {!Array<T>}
- * @template T
- */
- goog.array.join = function(var_args) {
- return Array.prototype.concat.apply([], arguments);
- };
- /**
- * Converts an object to an array.
- * @param {IArrayLike<T>|string} object The object to convert to an
- * array.
- * @return {!Array<T>} The object converted into an array. If object has a
- * length property, every property indexed with a non-negative number
- * less than length will be included in the result. If object does not
- * have a length property, an empty array will be returned.
- * @template T
- */
- goog.array.toArray = function(object) {
- var length = object.length;
- // If length is not a number the following it false. This case is kept for
- // backwards compatibility since there are callers that pass objects that are
- // not array like.
- if (length > 0) {
- var rv = new Array(length);
- for (var i = 0; i < length; i++) {
- rv[i] = object[i];
- }
- return rv;
- }
- return [];
- };
- /**
- * Does a shallow copy of an array.
- * @param {IArrayLike<T>|string} arr Array or array-like object to
- * clone.
- * @return {!Array<T>} Clone of the input array.
- * @template T
- */
- goog.array.clone = goog.array.toArray;
- /**
- * Extends an array with another array, element, or "array like" object.
- * This function operates 'in-place', it does not create a new Array.
- *
- * Example:
- * var a = [];
- * goog.array.extend(a, [0, 1]);
- * a; // [0, 1]
- * goog.array.extend(a, 2);
- * a; // [0, 1, 2]
- *
- * @param {Array<VALUE>} arr1 The array to modify.
- * @param {...(Array<VALUE>|VALUE)} var_args The elements or arrays of elements
- * to add to arr1.
- * @template VALUE
- */
- goog.array.extend = function(arr1, var_args) {
- for (var i = 1; i < arguments.length; i++) {
- var arr2 = arguments[i];
- if (goog.isArrayLike(arr2)) {
- var len1 = arr1.length || 0;
- var len2 = arr2.length || 0;
- arr1.length = len1 + len2;
- for (var j = 0; j < len2; j++) {
- arr1[len1 + j] = arr2[j];
- }
- } else {
- arr1.push(arr2);
- }
- }
- };
- /**
- * Adds or removes elements from an array. This is a generic version of Array
- * splice. This means that it might work on other objects similar to arrays,
- * such as the arguments object.
- *
- * @param {IArrayLike<T>} arr The array to modify.
- * @param {number|undefined} index The index at which to start changing the
- * array. If not defined, treated as 0.
- * @param {number} howMany How many elements to remove (0 means no removal. A
- * value below 0 is treated as zero and so is any other non number. Numbers
- * are floored).
- * @param {...T} var_args Optional, additional elements to insert into the
- * array.
- * @return {!Array<T>} the removed elements.
- * @template T
- */
- goog.array.splice = function(arr, index, howMany, var_args) {
- goog.asserts.assert(arr.length != null);
- return Array.prototype.splice.apply(arr, goog.array.slice(arguments, 1));
- };
- /**
- * Returns a new array from a segment of an array. This is a generic version of
- * Array slice. This means that it might work on other objects similar to
- * arrays, such as the arguments object.
- *
- * @param {IArrayLike<T>|string} arr The array from
- * which to copy a segment.
- * @param {number} start The index of the first element to copy.
- * @param {number=} opt_end The index after the last element to copy.
- * @return {!Array<T>} A new array containing the specified segment of the
- * original array.
- * @template T
- */
- goog.array.slice = function(arr, start, opt_end) {
- goog.asserts.assert(arr.length != null);
- // passing 1 arg to slice is not the same as passing 2 where the second is
- // null or undefined (in that case the second argument is treated as 0).
- // we could use slice on the arguments object and then use apply instead of
- // testing the length
- if (arguments.length <= 2) {
- return Array.prototype.slice.call(arr, start);
- } else {
- return Array.prototype.slice.call(arr, start, opt_end);
- }
- };
- /**
- * Removes all duplicates from an array (retaining only the first
- * occurrence of each array element). This function modifies the
- * array in place and doesn't change the order of the non-duplicate items.
- *
- * For objects, duplicates are identified as having the same unique ID as
- * defined by {@link goog.getUid}.
- *
- * Alternatively you can specify a custom hash function that returns a unique
- * value for each item in the array it should consider unique.
- *
- * Runtime: N,
- * Worstcase space: 2N (no dupes)
- *
- * @param {IArrayLike<T>} arr The array from which to remove
- * duplicates.
- * @param {Array=} opt_rv An optional array in which to return the results,
- * instead of performing the removal inplace. If specified, the original
- * array will remain unchanged.
- * @param {function(T):string=} opt_hashFn An optional function to use to
- * apply to every item in the array. This function should return a unique
- * value for each item in the array it should consider unique.
- * @template T
- */
- goog.array.removeDuplicates = function(arr, opt_rv, opt_hashFn) {
- var returnArray = opt_rv || arr;
- var defaultHashFn = function(item) {
- // Prefix each type with a single character representing the type to
- // prevent conflicting keys (e.g. true and 'true').
- return goog.isObject(item) ? 'o' + goog.getUid(item) :
- (typeof item).charAt(0) + item;
- };
- var hashFn = opt_hashFn || defaultHashFn;
- var seen = {}, cursorInsert = 0, cursorRead = 0;
- while (cursorRead < arr.length) {
- var current = arr[cursorRead++];
- var key = hashFn(current);
- if (!Object.prototype.hasOwnProperty.call(seen, key)) {
- seen[key] = true;
- returnArray[cursorInsert++] = current;
- }
- }
- returnArray.length = cursorInsert;
- };
- /**
- * Searches the specified array for the specified target using the binary
- * search algorithm. If no opt_compareFn is specified, elements are compared
- * using <code>goog.array.defaultCompare</code>, which compares the elements
- * using the built in < and > operators. This will produce the expected
- * behavior for homogeneous arrays of String(s) and Number(s). The array
- * specified <b>must</b> be sorted in ascending order (as defined by the
- * comparison function). If the array is not sorted, results are undefined.
- * If the array contains multiple instances of the specified target value, any
- * of these instances may be found.
- *
- * Runtime: O(log n)
- *
- * @param {IArrayLike<VALUE>} arr The array to be searched.
- * @param {TARGET} target The sought value.
- * @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison
- * function by which the array is ordered. Should take 2 arguments to
- * compare, and return a negative number, zero, or a positive number
- * depending on whether the first argument is less than, equal to, or
- * greater than the second.
- * @return {number} Lowest index of the target value if found, otherwise
- * (-(insertion point) - 1). The insertion point is where the value should
- * be inserted into arr to preserve the sorted property. Return value >= 0
- * iff target is found.
- * @template TARGET, VALUE
- */
- goog.array.binarySearch = function(arr, target, opt_compareFn) {
- return goog.array.binarySearch_(
- arr, opt_compareFn || goog.array.defaultCompare, false /* isEvaluator */,
- target);
- };
- /**
- * Selects an index in the specified array using the binary search algorithm.
- * The evaluator receives an element and determines whether the desired index
- * is before, at, or after it. The evaluator must be consistent (formally,
- * goog.array.map(goog.array.map(arr, evaluator, opt_obj), goog.math.sign)
- * must be monotonically non-increasing).
- *
- * Runtime: O(log n)
- *
- * @param {IArrayLike<VALUE>} arr The array to be searched.
- * @param {function(this:THIS, VALUE, number, ?): number} evaluator
- * Evaluator function that receives 3 arguments (the element, the index and
- * the array). Should return a negative number, zero, or a positive number
- * depending on whether the desired index is before, at, or after the
- * element passed to it.
- * @param {THIS=} opt_obj The object to be used as the value of 'this'
- * within evaluator.
- * @return {number} Index of the leftmost element matched by the evaluator, if
- * such exists; otherwise (-(insertion point) - 1). The insertion point is
- * the index of the first element for which the evaluator returns negative,
- * or arr.length if no such element exists. The return value is non-negative
- * iff a match is found.
- * @template THIS, VALUE
- */
- goog.array.binarySelect = function(arr, evaluator, opt_obj) {
- return goog.array.binarySearch_(
- arr, evaluator, true /* isEvaluator */, undefined /* opt_target */,
- opt_obj);
- };
- /**
- * Implementation of a binary search algorithm which knows how to use both
- * comparison functions and evaluators. If an evaluator is provided, will call
- * the evaluator with the given optional data object, conforming to the
- * interface defined in binarySelect. Otherwise, if a comparison function is
- * provided, will call the comparison function against the given data object.
- *
- * This implementation purposefully does not use goog.bind or goog.partial for
- * performance reasons.
- *
- * Runtime: O(log n)
- *
- * @param {IArrayLike<?>} arr The array to be searched.
- * @param {function(?, ?, ?): number | function(?, ?): number} compareFn
- * Either an evaluator or a comparison function, as defined by binarySearch
- * and binarySelect above.
- * @param {boolean} isEvaluator Whether the function is an evaluator or a
- * comparison function.
- * @param {?=} opt_target If the function is a comparison function, then
- * this is the target to binary search for.
- * @param {Object=} opt_selfObj If the function is an evaluator, this is an
- * optional this object for the evaluator.
- * @return {number} Lowest index of the target value if found, otherwise
- * (-(insertion point) - 1). The insertion point is where the value should
- * be inserted into arr to preserve the sorted property. Return value >= 0
- * iff target is found.
- * @private
- */
- goog.array.binarySearch_ = function(
- arr, compareFn, isEvaluator, opt_target, opt_selfObj) {
- var left = 0; // inclusive
- var right = arr.length; // exclusive
- var found;
- while (left < right) {
- var middle = (left + right) >> 1;
- var compareResult;
- if (isEvaluator) {
- compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);
- } else {
- // NOTE(dimvar): To avoid this cast, we'd have to use function overloading
- // for the type of binarySearch_, which the type system can't express yet.
- compareResult = /** @type {function(?, ?): number} */ (compareFn)(
- opt_target, arr[middle]);
- }
- if (compareResult > 0) {
- left = middle + 1;
- } else {
- right = middle;
- // We are looking for the lowest index so we can't return immediately.
- found = !compareResult;
- }
- }
- // left is the index if found, or the insertion point otherwise.
- // ~left is a shorthand for -left - 1.
- return found ? left : ~left;
- };
- /**
- * Sorts the specified array into ascending order. If no opt_compareFn is
- * specified, elements are compared using
- * <code>goog.array.defaultCompare</code>, which compares the elements using
- * the built in < and > operators. This will produce the expected behavior
- * for homogeneous arrays of String(s) and Number(s), unlike the native sort,
- * but will give unpredictable results for heterogeneous lists of strings and
- * numbers with different numbers of digits.
- *
- * This sort is not guaranteed to be stable.
- *
- * Runtime: Same as <code>Array.prototype.sort</code>
- *
- * @param {Array<T>} arr The array to be sorted.
- * @param {?function(T,T):number=} opt_compareFn Optional comparison
- * function by which the
- * array is to be ordered. Should take 2 arguments to compare, and return a
- * negative number, zero, or a positive number depending on whether the
- * first argument is less than, equal to, or greater than the second.
- * @template T
- */
- goog.array.sort = function(arr, opt_compareFn) {
- // TODO(arv): Update type annotation since null is not accepted.
- arr.sort(opt_compareFn || goog.array.defaultCompare);
- };
- /**
- * Sorts the specified array into ascending order in a stable way. If no
- * opt_compareFn is specified, elements are compared using
- * <code>goog.array.defaultCompare</code>, which compares the elements using
- * the built in < and > operators. This will produce the expected behavior
- * for homogeneous arrays of String(s) and Number(s).
- *
- * Runtime: Same as <code>Array.prototype.sort</code>, plus an additional
- * O(n) overhead of copying the array twice.
- *
- * @param {Array<T>} arr The array to be sorted.
- * @param {?function(T, T): number=} opt_compareFn Optional comparison function
- * by which the array is to be ordered. Should take 2 arguments to compare,
- * and return a negative number, zero, or a positive number depending on
- * whether the first argument is less than, equal to, or greater than the
- * second.
- * @template T
- */
- goog.array.stableSort = function(arr, opt_compareFn) {
- var compArr = new Array(arr.length);
- for (var i = 0; i < arr.length; i++) {
- compArr[i] = {index: i, value: arr[i]};
- }
- var valueCompareFn = opt_compareFn || goog.array.defaultCompare;
- function stableCompareFn(obj1, obj2) {
- return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;
- }
- goog.array.sort(compArr, stableCompareFn);
- for (var i = 0; i < arr.length; i++) {
- arr[i] = compArr[i].value;
- }
- };
- /**
- * Sort the specified array into ascending order based on item keys
- * returned by the specified key function.
- * If no opt_compareFn is specified, the keys are compared in ascending order
- * using <code>goog.array.defaultCompare</code>.
- *
- * Runtime: O(S(f(n)), where S is runtime of <code>goog.array.sort</code>
- * and f(n) is runtime of the key function.
- *
- * @param {Array<T>} arr The array to be sorted.
- * @param {function(T): K} keyFn Function taking array element and returning
- * a key used for sorting this element.
- * @param {?function(K, K): number=} opt_compareFn Optional comparison function
- * by which the keys are to be ordered. Should take 2 arguments to compare,
- * and return a negative number, zero, or a positive number depending on
- * whether the first argument is less than, equal to, or greater than the
- * second.
- * @template T,K
- */
- goog.array.sortByKey = function(arr, keyFn, opt_compareFn) {
- var keyCompareFn = opt_compareFn || goog.array.defaultCompare;
- goog.array.sort(
- arr, function(a, b) { return keyCompareFn(keyFn(a), keyFn(b)); });
- };
- /**
- * Sorts an array of objects by the specified object key and compare
- * function. If no compare function is provided, the key values are
- * compared in ascending order using <code>goog.array.defaultCompare</code>.
- * This won't work for keys that get renamed by the compiler. So use
- * {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.
- * @param {Array<Object>} arr An array of objects to sort.
- * @param {string} key The object key to sort by.
- * @param {Function=} opt_compareFn The function to use to compare key
- * values.
- */
- goog.array.sortObjectsByKey = function(arr, key, opt_compareFn) {
- goog.array.sortByKey(arr, function(obj) { return obj[key]; }, opt_compareFn);
- };
- /**
- * Tells if the array is sorted.
- * @param {!Array<T>} arr The array.
- * @param {?function(T,T):number=} opt_compareFn Function to compare the
- * array elements.
- * Should take 2 arguments to compare, and return a negative number, zero,
- * or a positive number depending on whether the first argument is less
- * than, equal to, or greater than the second.
- * @param {boolean=} opt_strict If true no equal elements are allowed.
- * @return {boolean} Whether the array is sorted.
- * @template T
- */
- goog.array.isSorted = function(arr, opt_compareFn, opt_strict) {
- var compare = opt_compareFn || goog.array.defaultCompare;
- for (var i = 1; i < arr.length; i++) {
- var compareResult = compare(arr[i - 1], arr[i]);
- if (compareResult > 0 || compareResult == 0 && opt_strict) {
- return false;
- }
- }
- return true;
- };
- /**
- * Compares two arrays for equality. Two arrays are considered equal if they
- * have the same length and their corresponding elements are equal according to
- * the comparison function.
- *
- * @param {IArrayLike<?>} arr1 The first array to compare.
- * @param {IArrayLike<?>} arr2 The second array to compare.
- * @param {Function=} opt_equalsFn Optional comparison function.
- * Should take 2 arguments to compare, and return true if the arguments
- * are equal. Defaults to {@link goog.array.defaultCompareEquality} which
- * compares the elements using the built-in '===' operator.
- * @return {boolean} Whether the two arrays are equal.
- */
- goog.array.equals = function(arr1, arr2, opt_equalsFn) {
- if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||
- arr1.length != arr2.length) {
- return false;
- }
- var l = arr1.length;
- var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality;
- for (var i = 0; i < l; i++) {
- if (!equalsFn(arr1[i], arr2[i])) {
- return false;
- }
- }
- return true;
- };
- /**
- * 3-way array compare function.
- * @param {!IArrayLike<VALUE>} arr1 The first array to
- * compare.
- * @param {!IArrayLike<VALUE>} arr2 The second array to
- * compare.
- * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
- * function by which the array is to be ordered. Should take 2 arguments to
- * compare, and return a negative number, zero, or a positive number
- * depending on whether the first argument is less than, equal to, or
- * greater than the second.
- * @return {number} Negative number, zero, or a positive number depending on
- * whether the first argument is less than, equal to, or greater than the
- * second.
- * @template VALUE
- */
- goog.array.compare3 = function(arr1, arr2, opt_compareFn) {
- var compare = opt_compareFn || goog.array.defaultCompare;
- var l = Math.min(arr1.length, arr2.length);
- for (var i = 0; i < l; i++) {
- var result = compare(arr1[i], arr2[i]);
- if (result != 0) {
- return result;
- }
- }
- return goog.array.defaultCompare(arr1.length, arr2.length);
- };
- /**
- * Compares its two arguments for order, using the built in < and >
- * operators.
- * @param {VALUE} a The first object to be compared.
- * @param {VALUE} b The second object to be compared.
- * @return {number} A negative number, zero, or a positive number as the first
- * argument is less than, equal to, or greater than the second,
- * respectively.
- * @template VALUE
- */
- goog.array.defaultCompare = function(a, b) {
- return a > b ? 1 : a < b ? -1 : 0;
- };
- /**
- * Compares its two arguments for inverse order, using the built in < and >
- * operators.
- * @param {VALUE} a The first object to be compared.
- * @param {VALUE} b The second object to be compared.
- * @return {number} A negative number, zero, or a positive number as the first
- * argument is greater than, equal to, or less than the second,
- * respectively.
- * @template VALUE
- */
- goog.array.inverseDefaultCompare = function(a, b) {
- return -goog.array.defaultCompare(a, b);
- };
- /**
- * Compares its two arguments for equality, using the built in === operator.
- * @param {*} a The first object to compare.
- * @param {*} b The second object to compare.
- * @return {boolean} True if the two arguments are equal, false otherwise.
- */
- goog.array.defaultCompareEquality = function(a, b) {
- return a === b;
- };
- /**
- * Inserts a value into a sorted array. The array is not modified if the
- * value is already present.
- * @param {IArrayLike<VALUE>} array The array to modify.
- * @param {VALUE} value The object to insert.
- * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
- * function by which the array is ordered. Should take 2 arguments to
- * compare, and return a negative number, zero, or a positive number
- * depending on whether the first argument is less than, equal to, or
- * greater than the second.
- * @return {boolean} True if an element was inserted.
- * @template VALUE
- */
- goog.array.binaryInsert = function(array, value, opt_compareFn) {
- var index = goog.array.binarySearch(array, value, opt_compareFn);
- if (index < 0) {
- goog.array.insertAt(array, value, -(index + 1));
- return true;
- }
- return false;
- };
- /**
- * Removes a value from a sorted array.
- * @param {!IArrayLike<VALUE>} array The array to modify.
- * @param {VALUE} value The object to remove.
- * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
- * function by which the array is ordered. Should take 2 arguments to
- * compare, and return a negative number, zero, or a positive number
- * depending on whether the first argument is less than, equal to, or
- * greater than the second.
- * @return {boolean} True if an element was removed.
- * @template VALUE
- */
- goog.array.binaryRemove = function(array, value, opt_compareFn) {
- var index = goog.array.binarySearch(array, value, opt_compareFn);
- return (index >= 0) ? goog.array.removeAt(array, index) : false;
- };
- /**
- * Splits an array into disjoint buckets according to a splitting function.
- * @param {Array<T>} array The array.
- * @param {function(this:S, T,number,Array<T>):?} sorter Function to call for
- * every element. This takes 3 arguments (the element, the index and the
- * array) and must return a valid object key (a string, number, etc), or
- * undefined, if that object should not be placed in a bucket.
- * @param {S=} opt_obj The object to be used as the value of 'this' within
- * sorter.
- * @return {!Object} An object, with keys being all of the unique return values
- * of sorter, and values being arrays containing the items for
- * which the splitter returned that key.
- * @template T,S
- */
- goog.array.bucket = function(array, sorter, opt_obj) {
- var buckets = {};
- for (var i = 0; i < array.length; i++) {
- var value = array[i];
- var key = sorter.call(/** @type {?} */ (opt_obj), value, i, array);
- if (goog.isDef(key)) {
- // Push the value to the right bucket, creating it if necessary.
- var bucket = buckets[key] || (buckets[key] = []);
- bucket.push(value);
- }
- }
- return buckets;
- };
- /**
- * Creates a new object built from the provided array and the key-generation
- * function.
- * @param {IArrayLike<T>} arr Array or array like object over
- * which to iterate whose elements will be the values in the new object.
- * @param {?function(this:S, T, number, ?) : string} keyFunc The function to
- * call for every element. This function takes 3 arguments (the element, the
- * index and the array) and should return a string that will be used as the
- * key for the element in the new object. If the function returns the same
- * key for more than one element, the value for that key is
- * implementation-defined.
- * @param {S=} opt_obj The object to be used as the value of 'this'
- * within keyFunc.
- * @return {!Object<T>} The new object.
- * @template T,S
- */
- goog.array.toObject = function(arr, keyFunc, opt_obj) {
- var ret = {};
- goog.array.forEach(arr, function(element, index) {
- ret[keyFunc.call(/** @type {?} */ (opt_obj), element, index, arr)] =
- element;
- });
- return ret;
- };
- /**
- * Creates a range of numbers in an arithmetic progression.
- *
- * Range takes 1, 2, or 3 arguments:
- * <pre>
- * range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]
- * range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]
- * range(-2, -5, -1) produces [-2, -3, -4]
- * range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.
- * </pre>
- *
- * @param {number} startOrEnd The starting value of the range if an end argument
- * is provided. Otherwise, the start value is 0, and this is the end value.
- * @param {number=} opt_end The optional end value of the range.
- * @param {number=} opt_step The step size between range values. Defaults to 1
- * if opt_step is undefined or 0.
- * @return {!Array<number>} An array of numbers for the requested range. May be
- * an empty array if adding the step would not converge toward the end
- * value.
- */
- goog.array.range = function(startOrEnd, opt_end, opt_step) {
- var array = [];
- var start = 0;
- var end = startOrEnd;
- var step = opt_step || 1;
- if (opt_end !== undefined) {
- start = startOrEnd;
- end = opt_end;
- }
- if (step * (end - start) < 0) {
- // Sign mismatch: start + step will never reach the end value.
- return [];
- }
- if (step > 0) {
- for (var i = start; i < end; i += step) {
- array.push(i);
- }
- } else {
- for (var i = start; i > end; i += step) {
- array.push(i);
- }
- }
- return array;
- };
- /**
- * Returns an array consisting of the given value repeated N times.
- *
- * @param {VALUE} value The value to repeat.
- * @param {number} n The repeat count.
- * @return {!Array<VALUE>} An array with the repeated value.
- * @template VALUE
- */
- goog.array.repeat = function(value, n) {
- var array = [];
- for (var i = 0; i < n; i++) {
- array[i] = value;
- }
- return array;
- };
- /**
- * Returns an array consisting of every argument with all arrays
- * expanded in-place recursively.
- *
- * @param {...*} var_args The values to flatten.
- * @return {!Array<?>} An array containing the flattened values.
- */
- goog.array.flatten = function(var_args) {
- var CHUNK_SIZE = 8192;
- var result = [];
- for (var i = 0; i < arguments.length; i++) {
- var element = arguments[i];
- if (goog.isArray(element)) {
- for (var c = 0; c < element.length; c += CHUNK_SIZE) {
- var chunk = goog.array.slice(element, c, c + CHUNK_SIZE);
- var recurseResult = goog.array.flatten.apply(null, chunk);
- for (var r = 0; r < recurseResult.length; r++) {
- result.push(recurseResult[r]);
- }
- }
- } else {
- result.push(element);
- }
- }
- return result;
- };
- /**
- * Rotates an array in-place. After calling this method, the element at
- * index i will be the element previously at index (i - n) %
- * array.length, for all values of i between 0 and array.length - 1,
- * inclusive.
- *
- * For example, suppose list comprises [t, a, n, k, s]. After invoking
- * rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].
- *
- * @param {!Array<T>} array The array to rotate.
- * @param {number} n The amount to rotate.
- * @return {!Array<T>} The array.
- * @template T
- */
- goog.array.rotate = function(array, n) {
- goog.asserts.assert(array.length != null);
- if (array.length) {
- n %= array.length;
- if (n > 0) {
- Array.prototype.unshift.apply(array, array.splice(-n, n));
- } else if (n < 0) {
- Array.prototype.push.apply(array, array.splice(0, -n));
- }
- }
- return array;
- };
- /**
- * Moves one item of an array to a new position keeping the order of the rest
- * of the items. Example use case: keeping a list of JavaScript objects
- * synchronized with the corresponding list of DOM elements after one of the
- * elements has been dragged to a new position.
- * @param {!IArrayLike<?>} arr The array to modify.
- * @param {number} fromIndex Index of the item to move between 0 and
- * {@code arr.length - 1}.
- * @param {number} toIndex Target index between 0 and {@code arr.length - 1}.
- */
- goog.array.moveItem = function(arr, fromIndex, toIndex) {
- goog.asserts.assert(fromIndex >= 0 && fromIndex < arr.length);
- goog.asserts.assert(toIndex >= 0 && toIndex < arr.length);
- // Remove 1 item at fromIndex.
- var removedItems = Array.prototype.splice.call(arr, fromIndex, 1);
- // Insert the removed item at toIndex.
- Array.prototype.splice.call(arr, toIndex, 0, removedItems[0]);
- // We don't use goog.array.insertAt and goog.array.removeAt, because they're
- // significantly slower than splice.
- };
- /**
- * Creates a new array for which the element at position i is an array of the
- * ith element of the provided arrays. The returned array will only be as long
- * as the shortest array provided; additional values are ignored. For example,
- * the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].
- *
- * This is similar to the zip() function in Python. See {@link
- * http://docs.python.org/library/functions.html#zip}
- *
- * @param {...!IArrayLike<?>} var_args Arrays to be combined.
- * @return {!Array<!Array<?>>} A new array of arrays created from
- * provided arrays.
- */
- goog.array.zip = function(var_args) {
- if (!arguments.length) {
- return [];
- }
- var result = [];
- var minLen = arguments[0].length;
- for (var i = 1; i < arguments.length; i++) {
- if (arguments[i].length < minLen) {
- minLen = arguments[i].length;
- }
- }
- for (var i = 0; i < minLen; i++) {
- var value = [];
- for (var j = 0; j < arguments.length; j++) {
- value.push(arguments[j][i]);
- }
- result.push(value);
- }
- return result;
- };
- /**
- * Shuffles the values in the specified array using the Fisher-Yates in-place
- * shuffle (also known as the Knuth Shuffle). By default, calls Math.random()
- * and so resets the state of that random number generator. Similarly, may reset
- * the state of the any other specified random number generator.
- *
- * Runtime: O(n)
- *
- * @param {!Array<?>} arr The array to be shuffled.
- * @param {function():number=} opt_randFn Optional random function to use for
- * shuffling.
- * Takes no arguments, and returns a random number on the interval [0, 1).
- * Defaults to Math.random() using JavaScript's built-in Math library.
- */
- goog.array.shuffle = function(arr, opt_randFn) {
- var randFn = opt_randFn || Math.random;
- for (var i = arr.length - 1; i > 0; i--) {
- // Choose a random array index in [0, i] (inclusive with i).
- var j = Math.floor(randFn() * (i + 1));
- var tmp = arr[i];
- arr[i] = arr[j];
- arr[j] = tmp;
- }
- };
- /**
- * Returns a new array of elements from arr, based on the indexes of elements
- * provided by index_arr. For example, the result of index copying
- * ['a', 'b', 'c'] with index_arr [1,0,0,2] is ['b', 'a', 'a', 'c'].
- *
- * @param {!Array<T>} arr The array to get a indexed copy from.
- * @param {!Array<number>} index_arr An array of indexes to get from arr.
- * @return {!Array<T>} A new array of elements from arr in index_arr order.
- * @template T
- */
- goog.array.copyByIndex = function(arr, index_arr) {
- var result = [];
- goog.array.forEach(index_arr, function(index) { result.push(arr[index]); });
- return result;
- };
- /**
- * Maps each element of the input array into zero or more elements of the output
- * array.
- *
- * @param {!IArrayLike<VALUE>|string} arr Array or array like object
- * over which to iterate.
- * @param {function(this:THIS, VALUE, number, ?): !Array<RESULT>} f The function
- * to call for every element. This function takes 3 arguments (the element,
- * the index and the array) and should return an array. The result will be
- * used to extend a new array.
- * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.
- * @return {!Array<RESULT>} a new array with the concatenation of all arrays
- * returned from f.
- * @template THIS, VALUE, RESULT
- */
- goog.array.concatMap = function(arr, f, opt_obj) {
- return goog.array.concat.apply([], goog.array.map(arr, f, opt_obj));
- };
|