array.js 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665
  1. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Utilities for manipulating arrays.
  16. *
  17. * @author arv@google.com (Erik Arvidsson)
  18. */
  19. goog.provide('goog.array');
  20. goog.require('goog.asserts');
  21. /**
  22. * @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should
  23. * rely on Array.prototype functions, if available.
  24. *
  25. * The Array.prototype functions can be defined by external libraries like
  26. * Prototype and setting this flag to false forces closure to use its own
  27. * goog.array implementation.
  28. *
  29. * If your javascript can be loaded by a third party site and you are wary about
  30. * relying on the prototype functions, specify
  31. * "--define goog.NATIVE_ARRAY_PROTOTYPES=false" to the JSCompiler.
  32. *
  33. * Setting goog.TRUSTED_SITE to false will automatically set
  34. * NATIVE_ARRAY_PROTOTYPES to false.
  35. */
  36. goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE);
  37. /**
  38. * @define {boolean} If true, JSCompiler will use the native implementation of
  39. * array functions where appropriate (e.g., {@code Array#filter}) and remove the
  40. * unused pure JS implementation.
  41. */
  42. goog.define('goog.array.ASSUME_NATIVE_FUNCTIONS', false);
  43. /**
  44. * Returns the last element in an array without removing it.
  45. * Same as goog.array.last.
  46. * @param {IArrayLike<T>|string} array The array.
  47. * @return {T} Last item in array.
  48. * @template T
  49. */
  50. goog.array.peek = function(array) {
  51. return array[array.length - 1];
  52. };
  53. /**
  54. * Returns the last element in an array without removing it.
  55. * Same as goog.array.peek.
  56. * @param {IArrayLike<T>|string} array The array.
  57. * @return {T} Last item in array.
  58. * @template T
  59. */
  60. goog.array.last = goog.array.peek;
  61. // NOTE(arv): Since most of the array functions are generic it allows you to
  62. // pass an array-like object. Strings have a length and are considered array-
  63. // like. However, the 'in' operator does not work on strings so we cannot just
  64. // use the array path even if the browser supports indexing into strings. We
  65. // therefore end up splitting the string.
  66. /**
  67. * Returns the index of the first element of an array with a specified value, or
  68. * -1 if the element is not present in the array.
  69. *
  70. * See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}
  71. *
  72. * @param {IArrayLike<T>|string} arr The array to be searched.
  73. * @param {T} obj The object for which we are searching.
  74. * @param {number=} opt_fromIndex The index at which to start the search. If
  75. * omitted the search starts at index 0.
  76. * @return {number} The index of the first matching array element.
  77. * @template T
  78. */
  79. goog.array.indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&
  80. (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.indexOf) ?
  81. function(arr, obj, opt_fromIndex) {
  82. goog.asserts.assert(arr.length != null);
  83. return Array.prototype.indexOf.call(arr, obj, opt_fromIndex);
  84. } :
  85. function(arr, obj, opt_fromIndex) {
  86. var fromIndex = opt_fromIndex == null ?
  87. 0 :
  88. (opt_fromIndex < 0 ? Math.max(0, arr.length + opt_fromIndex) :
  89. opt_fromIndex);
  90. if (goog.isString(arr)) {
  91. // Array.prototype.indexOf uses === so only strings should be found.
  92. if (!goog.isString(obj) || obj.length != 1) {
  93. return -1;
  94. }
  95. return arr.indexOf(obj, fromIndex);
  96. }
  97. for (var i = fromIndex; i < arr.length; i++) {
  98. if (i in arr && arr[i] === obj) return i;
  99. }
  100. return -1;
  101. };
  102. /**
  103. * Returns the index of the last element of an array with a specified value, or
  104. * -1 if the element is not present in the array.
  105. *
  106. * See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof}
  107. *
  108. * @param {!IArrayLike<T>|string} arr The array to be searched.
  109. * @param {T} obj The object for which we are searching.
  110. * @param {?number=} opt_fromIndex The index at which to start the search. If
  111. * omitted the search starts at the end of the array.
  112. * @return {number} The index of the last matching array element.
  113. * @template T
  114. */
  115. goog.array.lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&
  116. (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.lastIndexOf) ?
  117. function(arr, obj, opt_fromIndex) {
  118. goog.asserts.assert(arr.length != null);
  119. // Firefox treats undefined and null as 0 in the fromIndex argument which
  120. // leads it to always return -1
  121. var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;
  122. return Array.prototype.lastIndexOf.call(arr, obj, fromIndex);
  123. } :
  124. function(arr, obj, opt_fromIndex) {
  125. var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;
  126. if (fromIndex < 0) {
  127. fromIndex = Math.max(0, arr.length + fromIndex);
  128. }
  129. if (goog.isString(arr)) {
  130. // Array.prototype.lastIndexOf uses === so only strings should be found.
  131. if (!goog.isString(obj) || obj.length != 1) {
  132. return -1;
  133. }
  134. return arr.lastIndexOf(obj, fromIndex);
  135. }
  136. for (var i = fromIndex; i >= 0; i--) {
  137. if (i in arr && arr[i] === obj) return i;
  138. }
  139. return -1;
  140. };
  141. /**
  142. * Calls a function for each element in an array. Skips holes in the array.
  143. * See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}
  144. *
  145. * @param {IArrayLike<T>|string} arr Array or array like object over
  146. * which to iterate.
  147. * @param {?function(this: S, T, number, ?): ?} f The function to call for every
  148. * element. This function takes 3 arguments (the element, the index and the
  149. * array). The return value is ignored.
  150. * @param {S=} opt_obj The object to be used as the value of 'this' within f.
  151. * @template T,S
  152. */
  153. goog.array.forEach = goog.NATIVE_ARRAY_PROTOTYPES &&
  154. (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.forEach) ?
  155. function(arr, f, opt_obj) {
  156. goog.asserts.assert(arr.length != null);
  157. Array.prototype.forEach.call(arr, f, opt_obj);
  158. } :
  159. function(arr, f, opt_obj) {
  160. var l = arr.length; // must be fixed during loop... see docs
  161. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  162. for (var i = 0; i < l; i++) {
  163. if (i in arr2) {
  164. f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);
  165. }
  166. }
  167. };
  168. /**
  169. * Calls a function for each element in an array, starting from the last
  170. * element rather than the first.
  171. *
  172. * @param {IArrayLike<T>|string} arr Array or array
  173. * like object over which to iterate.
  174. * @param {?function(this: S, T, number, ?): ?} f The function to call for every
  175. * element. This function
  176. * takes 3 arguments (the element, the index and the array). The return
  177. * value is ignored.
  178. * @param {S=} opt_obj The object to be used as the value of 'this'
  179. * within f.
  180. * @template T,S
  181. */
  182. goog.array.forEachRight = function(arr, f, opt_obj) {
  183. var l = arr.length; // must be fixed during loop... see docs
  184. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  185. for (var i = l - 1; i >= 0; --i) {
  186. if (i in arr2) {
  187. f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);
  188. }
  189. }
  190. };
  191. /**
  192. * Calls a function for each element in an array, and if the function returns
  193. * true adds the element to a new array.
  194. *
  195. * See {@link http://tinyurl.com/developer-mozilla-org-array-filter}
  196. *
  197. * @param {IArrayLike<T>|string} arr Array or array
  198. * like object over which to iterate.
  199. * @param {?function(this:S, T, number, ?):boolean} f The function to call for
  200. * every element. This function
  201. * takes 3 arguments (the element, the index and the array) and must
  202. * return a Boolean. If the return value is true the element is added to the
  203. * result array. If it is false the element is not included.
  204. * @param {S=} opt_obj The object to be used as the value of 'this'
  205. * within f.
  206. * @return {!Array<T>} a new array in which only elements that passed the test
  207. * are present.
  208. * @template T,S
  209. */
  210. goog.array.filter = goog.NATIVE_ARRAY_PROTOTYPES &&
  211. (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.filter) ?
  212. function(arr, f, opt_obj) {
  213. goog.asserts.assert(arr.length != null);
  214. return Array.prototype.filter.call(arr, f, opt_obj);
  215. } :
  216. function(arr, f, opt_obj) {
  217. var l = arr.length; // must be fixed during loop... see docs
  218. var res = [];
  219. var resLength = 0;
  220. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  221. for (var i = 0; i < l; i++) {
  222. if (i in arr2) {
  223. var val = arr2[i]; // in case f mutates arr2
  224. if (f.call(/** @type {?} */ (opt_obj), val, i, arr)) {
  225. res[resLength++] = val;
  226. }
  227. }
  228. }
  229. return res;
  230. };
  231. /**
  232. * Calls a function for each element in an array and inserts the result into a
  233. * new array.
  234. *
  235. * See {@link http://tinyurl.com/developer-mozilla-org-array-map}
  236. *
  237. * @param {IArrayLike<VALUE>|string} arr Array or array like object
  238. * over which to iterate.
  239. * @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call
  240. * for every element. This function takes 3 arguments (the element,
  241. * the index and the array) and should return something. The result will be
  242. * inserted into a new array.
  243. * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.
  244. * @return {!Array<RESULT>} a new array with the results from f.
  245. * @template THIS, VALUE, RESULT
  246. */
  247. goog.array.map = goog.NATIVE_ARRAY_PROTOTYPES &&
  248. (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.map) ?
  249. function(arr, f, opt_obj) {
  250. goog.asserts.assert(arr.length != null);
  251. return Array.prototype.map.call(arr, f, opt_obj);
  252. } :
  253. function(arr, f, opt_obj) {
  254. var l = arr.length; // must be fixed during loop... see docs
  255. var res = new Array(l);
  256. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  257. for (var i = 0; i < l; i++) {
  258. if (i in arr2) {
  259. res[i] = f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);
  260. }
  261. }
  262. return res;
  263. };
  264. /**
  265. * Passes every element of an array into a function and accumulates the result.
  266. *
  267. * See {@link http://tinyurl.com/developer-mozilla-org-array-reduce}
  268. *
  269. * For example:
  270. * var a = [1, 2, 3, 4];
  271. * goog.array.reduce(a, function(r, v, i, arr) {return r + v;}, 0);
  272. * returns 10
  273. *
  274. * @param {IArrayLike<T>|string} arr Array or array
  275. * like object over which to iterate.
  276. * @param {function(this:S, R, T, number, ?) : R} f The function to call for
  277. * every element. This function
  278. * takes 4 arguments (the function's previous result or the initial value,
  279. * the value of the current array element, the current array index, and the
  280. * array itself)
  281. * function(previousValue, currentValue, index, array).
  282. * @param {?} val The initial value to pass into the function on the first call.
  283. * @param {S=} opt_obj The object to be used as the value of 'this'
  284. * within f.
  285. * @return {R} Result of evaluating f repeatedly across the values of the array.
  286. * @template T,S,R
  287. */
  288. goog.array.reduce = goog.NATIVE_ARRAY_PROTOTYPES &&
  289. (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduce) ?
  290. function(arr, f, val, opt_obj) {
  291. goog.asserts.assert(arr.length != null);
  292. if (opt_obj) {
  293. f = goog.bind(f, opt_obj);
  294. }
  295. return Array.prototype.reduce.call(arr, f, val);
  296. } :
  297. function(arr, f, val, opt_obj) {
  298. var rval = val;
  299. goog.array.forEach(arr, function(val, index) {
  300. rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);
  301. });
  302. return rval;
  303. };
  304. /**
  305. * Passes every element of an array into a function and accumulates the result,
  306. * starting from the last element and working towards the first.
  307. *
  308. * See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright}
  309. *
  310. * For example:
  311. * var a = ['a', 'b', 'c'];
  312. * goog.array.reduceRight(a, function(r, v, i, arr) {return r + v;}, '');
  313. * returns 'cba'
  314. *
  315. * @param {IArrayLike<T>|string} arr Array or array
  316. * like object over which to iterate.
  317. * @param {?function(this:S, R, T, number, ?) : R} f The function to call for
  318. * every element. This function
  319. * 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 the
  321. * 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} Object returned as a result of evaluating f repeatedly across the
  327. * values of the array.
  328. * @template T,S,R
  329. */
  330. goog.array.reduceRight = goog.NATIVE_ARRAY_PROTOTYPES &&
  331. (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduceRight) ?
  332. function(arr, f, val, opt_obj) {
  333. goog.asserts.assert(arr.length != null);
  334. goog.asserts.assert(f != null);
  335. if (opt_obj) {
  336. f = goog.bind(f, opt_obj);
  337. }
  338. return Array.prototype.reduceRight.call(arr, f, val);
  339. } :
  340. function(arr, f, val, opt_obj) {
  341. var rval = val;
  342. goog.array.forEachRight(arr, function(val, index) {
  343. rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);
  344. });
  345. return rval;
  346. };
  347. /**
  348. * Calls f for each element of an array. If any call returns true, some()
  349. * returns true (without checking the remaining elements). If all calls
  350. * return false, some() returns false.
  351. *
  352. * See {@link http://tinyurl.com/developer-mozilla-org-array-some}
  353. *
  354. * @param {IArrayLike<T>|string} arr Array or array
  355. * like object over which to iterate.
  356. * @param {?function(this:S, T, number, ?) : boolean} f The function to call for
  357. * for every element. This function takes 3 arguments (the element, the
  358. * index and the array) and should return a boolean.
  359. * @param {S=} opt_obj The object to be used as the value of 'this'
  360. * within f.
  361. * @return {boolean} true if any element passes the test.
  362. * @template T,S
  363. */
  364. goog.array.some = goog.NATIVE_ARRAY_PROTOTYPES &&
  365. (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.some) ?
  366. function(arr, f, opt_obj) {
  367. goog.asserts.assert(arr.length != null);
  368. return Array.prototype.some.call(arr, f, opt_obj);
  369. } :
  370. function(arr, f, opt_obj) {
  371. var l = arr.length; // must be fixed during loop... see docs
  372. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  373. for (var i = 0; i < l; i++) {
  374. if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {
  375. return true;
  376. }
  377. }
  378. return false;
  379. };
  380. /**
  381. * Call f for each element of an array. If all calls return true, every()
  382. * returns true. If any call returns false, every() returns false and
  383. * does not continue to check the remaining elements.
  384. *
  385. * See {@link http://tinyurl.com/developer-mozilla-org-array-every}
  386. *
  387. * @param {IArrayLike<T>|string} arr Array or array
  388. * like object over which to iterate.
  389. * @param {?function(this:S, T, number, ?) : boolean} f The function to call for
  390. * for every element. This function takes 3 arguments (the element, the
  391. * index and the array) and should return a boolean.
  392. * @param {S=} opt_obj The object to be used as the value of 'this'
  393. * within f.
  394. * @return {boolean} false if any element fails the test.
  395. * @template T,S
  396. */
  397. goog.array.every = goog.NATIVE_ARRAY_PROTOTYPES &&
  398. (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.every) ?
  399. function(arr, f, opt_obj) {
  400. goog.asserts.assert(arr.length != null);
  401. return Array.prototype.every.call(arr, f, opt_obj);
  402. } :
  403. function(arr, f, opt_obj) {
  404. var l = arr.length; // must be fixed during loop... see docs
  405. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  406. for (var i = 0; i < l; i++) {
  407. if (i in arr2 && !f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {
  408. return false;
  409. }
  410. }
  411. return true;
  412. };
  413. /**
  414. * Counts the array elements that fulfill the predicate, i.e. for which the
  415. * callback function returns true. Skips holes in the array.
  416. *
  417. * @param {!IArrayLike<T>|string} arr Array or array like object
  418. * over which to iterate.
  419. * @param {function(this: S, T, number, ?): boolean} f The function to call for
  420. * every element. Takes 3 arguments (the element, the index and the array).
  421. * @param {S=} opt_obj The object to be used as the value of 'this' within f.
  422. * @return {number} The number of the matching elements.
  423. * @template T,S
  424. */
  425. goog.array.count = function(arr, f, opt_obj) {
  426. var count = 0;
  427. goog.array.forEach(arr, function(element, index, arr) {
  428. if (f.call(/** @type {?} */ (opt_obj), element, index, arr)) {
  429. ++count;
  430. }
  431. }, opt_obj);
  432. return count;
  433. };
  434. /**
  435. * Search an array for the first element that satisfies a given condition and
  436. * return that element.
  437. * @param {IArrayLike<T>|string} arr Array or array
  438. * like object over which to iterate.
  439. * @param {?function(this:S, T, number, ?) : boolean} f The function to call
  440. * for every element. This function takes 3 arguments (the element, the
  441. * index and the array) and should return a boolean.
  442. * @param {S=} opt_obj An optional "this" context for the function.
  443. * @return {T|null} The first array element that passes the test, or null if no
  444. * element is found.
  445. * @template T,S
  446. */
  447. goog.array.find = function(arr, f, opt_obj) {
  448. var i = goog.array.findIndex(arr, f, opt_obj);
  449. return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];
  450. };
  451. /**
  452. * Search an array for the first element that satisfies a given condition and
  453. * return its index.
  454. * @param {IArrayLike<T>|string} arr Array or array
  455. * like object over which to iterate.
  456. * @param {?function(this:S, T, number, ?) : boolean} f The function to call for
  457. * every element. This function
  458. * takes 3 arguments (the element, the index and the array) and should
  459. * return a boolean.
  460. * @param {S=} opt_obj An optional "this" context for the function.
  461. * @return {number} The index of the first array element that passes the test,
  462. * or -1 if no element is found.
  463. * @template T,S
  464. */
  465. goog.array.findIndex = function(arr, f, opt_obj) {
  466. var l = arr.length; // must be fixed during loop... see docs
  467. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  468. for (var i = 0; i < l; i++) {
  469. if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {
  470. return i;
  471. }
  472. }
  473. return -1;
  474. };
  475. /**
  476. * Search an array (in reverse order) for the last element that satisfies a
  477. * given condition and return that element.
  478. * @param {IArrayLike<T>|string} arr Array or array
  479. * like object over which to iterate.
  480. * @param {?function(this:S, T, number, ?) : boolean} f The function to call
  481. * for every element. This function
  482. * takes 3 arguments (the element, the index and the array) and should
  483. * return a boolean.
  484. * @param {S=} opt_obj An optional "this" context for the function.
  485. * @return {T|null} The last array element that passes the test, or null if no
  486. * element is found.
  487. * @template T,S
  488. */
  489. goog.array.findRight = function(arr, f, opt_obj) {
  490. var i = goog.array.findIndexRight(arr, f, opt_obj);
  491. return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];
  492. };
  493. /**
  494. * Search an array (in reverse order) for the last element that satisfies a
  495. * given condition and return its index.
  496. * @param {IArrayLike<T>|string} arr Array or array
  497. * like object over which to iterate.
  498. * @param {?function(this:S, T, number, ?) : boolean} f The function to call
  499. * for every element. This function
  500. * takes 3 arguments (the element, the index and the array) and should
  501. * return a boolean.
  502. * @param {S=} opt_obj An optional "this" context for the function.
  503. * @return {number} The index of the last array element that passes the test,
  504. * or -1 if no element is found.
  505. * @template T,S
  506. */
  507. goog.array.findIndexRight = function(arr, f, opt_obj) {
  508. var l = arr.length; // must be fixed during loop... see docs
  509. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  510. for (var i = l - 1; i >= 0; i--) {
  511. if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {
  512. return i;
  513. }
  514. }
  515. return -1;
  516. };
  517. /**
  518. * Whether the array contains the given object.
  519. * @param {IArrayLike<?>|string} arr The array to test for the presence of the
  520. * element.
  521. * @param {*} obj The object for which to test.
  522. * @return {boolean} true if obj is present.
  523. */
  524. goog.array.contains = function(arr, obj) {
  525. return goog.array.indexOf(arr, obj) >= 0;
  526. };
  527. /**
  528. * Whether the array is empty.
  529. * @param {IArrayLike<?>|string} arr The array to test.
  530. * @return {boolean} true if empty.
  531. */
  532. goog.array.isEmpty = function(arr) {
  533. return arr.length == 0;
  534. };
  535. /**
  536. * Clears the array.
  537. * @param {IArrayLike<?>} arr Array or array like object to clear.
  538. */
  539. goog.array.clear = function(arr) {
  540. // For non real arrays we don't have the magic length so we delete the
  541. // indices.
  542. if (!goog.isArray(arr)) {
  543. for (var i = arr.length - 1; i >= 0; i--) {
  544. delete arr[i];
  545. }
  546. }
  547. arr.length = 0;
  548. };
  549. /**
  550. * Pushes an item into an array, if it's not already in the array.
  551. * @param {Array<T>} arr Array into which to insert the item.
  552. * @param {T} obj Value to add.
  553. * @template T
  554. */
  555. goog.array.insert = function(arr, obj) {
  556. if (!goog.array.contains(arr, obj)) {
  557. arr.push(obj);
  558. }
  559. };
  560. /**
  561. * Inserts an object at the given index of the array.
  562. * @param {IArrayLike<?>} arr The array to modify.
  563. * @param {*} obj The object to insert.
  564. * @param {number=} opt_i The index at which to insert the object. If omitted,
  565. * treated as 0. A negative index is counted from the end of the array.
  566. */
  567. goog.array.insertAt = function(arr, obj, opt_i) {
  568. goog.array.splice(arr, opt_i, 0, obj);
  569. };
  570. /**
  571. * Inserts at the given index of the array, all elements of another array.
  572. * @param {IArrayLike<?>} arr The array to modify.
  573. * @param {IArrayLike<?>} elementsToAdd The array of elements to add.
  574. * @param {number=} opt_i The index at which to insert the object. If omitted,
  575. * treated as 0. A negative index is counted from the end of the array.
  576. */
  577. goog.array.insertArrayAt = function(arr, elementsToAdd, opt_i) {
  578. goog.partial(goog.array.splice, arr, opt_i, 0).apply(null, elementsToAdd);
  579. };
  580. /**
  581. * Inserts an object into an array before a specified object.
  582. * @param {Array<T>} arr The array to modify.
  583. * @param {T} obj The object to insert.
  584. * @param {T=} opt_obj2 The object before which obj should be inserted. If obj2
  585. * is omitted or not found, obj is inserted at the end of the array.
  586. * @template T
  587. */
  588. goog.array.insertBefore = function(arr, obj, opt_obj2) {
  589. var i;
  590. if (arguments.length == 2 || (i = goog.array.indexOf(arr, opt_obj2)) < 0) {
  591. arr.push(obj);
  592. } else {
  593. goog.array.insertAt(arr, obj, i);
  594. }
  595. };
  596. /**
  597. * Removes the first occurrence of a particular value from an array.
  598. * @param {IArrayLike<T>} arr Array from which to remove
  599. * value.
  600. * @param {T} obj Object to remove.
  601. * @return {boolean} True if an element was removed.
  602. * @template T
  603. */
  604. goog.array.remove = function(arr, obj) {
  605. var i = goog.array.indexOf(arr, obj);
  606. var rv;
  607. if ((rv = i >= 0)) {
  608. goog.array.removeAt(arr, i);
  609. }
  610. return rv;
  611. };
  612. /**
  613. * Removes the last occurrence of a particular value from an array.
  614. * @param {!IArrayLike<T>} arr Array from which to remove value.
  615. * @param {T} obj Object to remove.
  616. * @return {boolean} True if an element was removed.
  617. * @template T
  618. */
  619. goog.array.removeLast = function(arr, obj) {
  620. var i = goog.array.lastIndexOf(arr, obj);
  621. if (i >= 0) {
  622. goog.array.removeAt(arr, i);
  623. return true;
  624. }
  625. return false;
  626. };
  627. /**
  628. * Removes from an array the element at index i
  629. * @param {IArrayLike<?>} arr Array or array like object from which to
  630. * remove value.
  631. * @param {number} i The index to remove.
  632. * @return {boolean} True if an element was removed.
  633. */
  634. goog.array.removeAt = function(arr, i) {
  635. goog.asserts.assert(arr.length != null);
  636. // use generic form of splice
  637. // splice returns the removed items and if successful the length of that
  638. // will be 1
  639. return Array.prototype.splice.call(arr, i, 1).length == 1;
  640. };
  641. /**
  642. * Removes the first value that satisfies the given condition.
  643. * @param {IArrayLike<T>} arr Array or array
  644. * like object over which to iterate.
  645. * @param {?function(this:S, T, number, ?) : boolean} f The function to call
  646. * for every element. This function
  647. * takes 3 arguments (the element, the index and the array) and should
  648. * return a boolean.
  649. * @param {S=} opt_obj An optional "this" context for the function.
  650. * @return {boolean} True if an element was removed.
  651. * @template T,S
  652. */
  653. goog.array.removeIf = function(arr, f, opt_obj) {
  654. var i = goog.array.findIndex(arr, f, opt_obj);
  655. if (i >= 0) {
  656. goog.array.removeAt(arr, i);
  657. return true;
  658. }
  659. return false;
  660. };
  661. /**
  662. * Removes all values that satisfy the given condition.
  663. * @param {IArrayLike<T>} arr Array or array
  664. * like object over which to iterate.
  665. * @param {?function(this:S, T, number, ?) : boolean} f The function to call
  666. * for every element. This function
  667. * takes 3 arguments (the element, the index and the array) and should
  668. * return a boolean.
  669. * @param {S=} opt_obj An optional "this" context for the function.
  670. * @return {number} The number of items removed
  671. * @template T,S
  672. */
  673. goog.array.removeAllIf = function(arr, f, opt_obj) {
  674. var removedCount = 0;
  675. goog.array.forEachRight(arr, function(val, index) {
  676. if (f.call(/** @type {?} */ (opt_obj), val, index, arr)) {
  677. if (goog.array.removeAt(arr, index)) {
  678. removedCount++;
  679. }
  680. }
  681. });
  682. return removedCount;
  683. };
  684. /**
  685. * Returns a new array that is the result of joining the arguments. If arrays
  686. * are passed then their items are added, however, if non-arrays are passed they
  687. * will be added to the return array as is.
  688. *
  689. * Note that ArrayLike objects will be added as is, rather than having their
  690. * items added.
  691. *
  692. * goog.array.concat([1, 2], [3, 4]) -> [1, 2, 3, 4]
  693. * goog.array.concat(0, [1, 2]) -> [0, 1, 2]
  694. * goog.array.concat([1, 2], null) -> [1, 2, null]
  695. *
  696. * There is bug in all current versions of IE (6, 7 and 8) where arrays created
  697. * in an iframe become corrupted soon (not immediately) after the iframe is
  698. * destroyed. This is common if loading data via goog.net.IframeIo, for example.
  699. * This corruption only affects the concat method which will start throwing
  700. * Catastrophic Errors (#-2147418113).
  701. *
  702. * See http://endoflow.com/scratch/corrupted-arrays.html for a test case.
  703. *
  704. * Internally goog.array should use this, so that all methods will continue to
  705. * work on these broken array objects.
  706. *
  707. * @param {...*} var_args Items to concatenate. Arrays will have each item
  708. * added, while primitives and objects will be added as is.
  709. * @return {!Array<?>} The new resultant array.
  710. */
  711. goog.array.concat = function(var_args) {
  712. return Array.prototype.concat.apply([], arguments);
  713. };
  714. /**
  715. * Returns a new array that contains the contents of all the arrays passed.
  716. * @param {...!Array<T>} var_args
  717. * @return {!Array<T>}
  718. * @template T
  719. */
  720. goog.array.join = function(var_args) {
  721. return Array.prototype.concat.apply([], arguments);
  722. };
  723. /**
  724. * Converts an object to an array.
  725. * @param {IArrayLike<T>|string} object The object to convert to an
  726. * array.
  727. * @return {!Array<T>} The object converted into an array. If object has a
  728. * length property, every property indexed with a non-negative number
  729. * less than length will be included in the result. If object does not
  730. * have a length property, an empty array will be returned.
  731. * @template T
  732. */
  733. goog.array.toArray = function(object) {
  734. var length = object.length;
  735. // If length is not a number the following it false. This case is kept for
  736. // backwards compatibility since there are callers that pass objects that are
  737. // not array like.
  738. if (length > 0) {
  739. var rv = new Array(length);
  740. for (var i = 0; i < length; i++) {
  741. rv[i] = object[i];
  742. }
  743. return rv;
  744. }
  745. return [];
  746. };
  747. /**
  748. * Does a shallow copy of an array.
  749. * @param {IArrayLike<T>|string} arr Array or array-like object to
  750. * clone.
  751. * @return {!Array<T>} Clone of the input array.
  752. * @template T
  753. */
  754. goog.array.clone = goog.array.toArray;
  755. /**
  756. * Extends an array with another array, element, or "array like" object.
  757. * This function operates 'in-place', it does not create a new Array.
  758. *
  759. * Example:
  760. * var a = [];
  761. * goog.array.extend(a, [0, 1]);
  762. * a; // [0, 1]
  763. * goog.array.extend(a, 2);
  764. * a; // [0, 1, 2]
  765. *
  766. * @param {Array<VALUE>} arr1 The array to modify.
  767. * @param {...(Array<VALUE>|VALUE)} var_args The elements or arrays of elements
  768. * to add to arr1.
  769. * @template VALUE
  770. */
  771. goog.array.extend = function(arr1, var_args) {
  772. for (var i = 1; i < arguments.length; i++) {
  773. var arr2 = arguments[i];
  774. if (goog.isArrayLike(arr2)) {
  775. var len1 = arr1.length || 0;
  776. var len2 = arr2.length || 0;
  777. arr1.length = len1 + len2;
  778. for (var j = 0; j < len2; j++) {
  779. arr1[len1 + j] = arr2[j];
  780. }
  781. } else {
  782. arr1.push(arr2);
  783. }
  784. }
  785. };
  786. /**
  787. * Adds or removes elements from an array. This is a generic version of Array
  788. * splice. This means that it might work on other objects similar to arrays,
  789. * such as the arguments object.
  790. *
  791. * @param {IArrayLike<T>} arr The array to modify.
  792. * @param {number|undefined} index The index at which to start changing the
  793. * array. If not defined, treated as 0.
  794. * @param {number} howMany How many elements to remove (0 means no removal. A
  795. * value below 0 is treated as zero and so is any other non number. Numbers
  796. * are floored).
  797. * @param {...T} var_args Optional, additional elements to insert into the
  798. * array.
  799. * @return {!Array<T>} the removed elements.
  800. * @template T
  801. */
  802. goog.array.splice = function(arr, index, howMany, var_args) {
  803. goog.asserts.assert(arr.length != null);
  804. return Array.prototype.splice.apply(arr, goog.array.slice(arguments, 1));
  805. };
  806. /**
  807. * Returns a new array from a segment of an array. This is a generic version of
  808. * Array slice. This means that it might work on other objects similar to
  809. * arrays, such as the arguments object.
  810. *
  811. * @param {IArrayLike<T>|string} arr The array from
  812. * which to copy a segment.
  813. * @param {number} start The index of the first element to copy.
  814. * @param {number=} opt_end The index after the last element to copy.
  815. * @return {!Array<T>} A new array containing the specified segment of the
  816. * original array.
  817. * @template T
  818. */
  819. goog.array.slice = function(arr, start, opt_end) {
  820. goog.asserts.assert(arr.length != null);
  821. // passing 1 arg to slice is not the same as passing 2 where the second is
  822. // null or undefined (in that case the second argument is treated as 0).
  823. // we could use slice on the arguments object and then use apply instead of
  824. // testing the length
  825. if (arguments.length <= 2) {
  826. return Array.prototype.slice.call(arr, start);
  827. } else {
  828. return Array.prototype.slice.call(arr, start, opt_end);
  829. }
  830. };
  831. /**
  832. * Removes all duplicates from an array (retaining only the first
  833. * occurrence of each array element). This function modifies the
  834. * array in place and doesn't change the order of the non-duplicate items.
  835. *
  836. * For objects, duplicates are identified as having the same unique ID as
  837. * defined by {@link goog.getUid}.
  838. *
  839. * Alternatively you can specify a custom hash function that returns a unique
  840. * value for each item in the array it should consider unique.
  841. *
  842. * Runtime: N,
  843. * Worstcase space: 2N (no dupes)
  844. *
  845. * @param {IArrayLike<T>} arr The array from which to remove
  846. * duplicates.
  847. * @param {Array=} opt_rv An optional array in which to return the results,
  848. * instead of performing the removal inplace. If specified, the original
  849. * array will remain unchanged.
  850. * @param {function(T):string=} opt_hashFn An optional function to use to
  851. * apply to every item in the array. This function should return a unique
  852. * value for each item in the array it should consider unique.
  853. * @template T
  854. */
  855. goog.array.removeDuplicates = function(arr, opt_rv, opt_hashFn) {
  856. var returnArray = opt_rv || arr;
  857. var defaultHashFn = function(item) {
  858. // Prefix each type with a single character representing the type to
  859. // prevent conflicting keys (e.g. true and 'true').
  860. return goog.isObject(item) ? 'o' + goog.getUid(item) :
  861. (typeof item).charAt(0) + item;
  862. };
  863. var hashFn = opt_hashFn || defaultHashFn;
  864. var seen = {}, cursorInsert = 0, cursorRead = 0;
  865. while (cursorRead < arr.length) {
  866. var current = arr[cursorRead++];
  867. var key = hashFn(current);
  868. if (!Object.prototype.hasOwnProperty.call(seen, key)) {
  869. seen[key] = true;
  870. returnArray[cursorInsert++] = current;
  871. }
  872. }
  873. returnArray.length = cursorInsert;
  874. };
  875. /**
  876. * Searches the specified array for the specified target using the binary
  877. * search algorithm. If no opt_compareFn is specified, elements are compared
  878. * using <code>goog.array.defaultCompare</code>, which compares the elements
  879. * using the built in < and > operators. This will produce the expected
  880. * behavior for homogeneous arrays of String(s) and Number(s). The array
  881. * specified <b>must</b> be sorted in ascending order (as defined by the
  882. * comparison function). If the array is not sorted, results are undefined.
  883. * If the array contains multiple instances of the specified target value, any
  884. * of these instances may be found.
  885. *
  886. * Runtime: O(log n)
  887. *
  888. * @param {IArrayLike<VALUE>} arr The array to be searched.
  889. * @param {TARGET} target The sought value.
  890. * @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison
  891. * function by which the array is ordered. Should take 2 arguments to
  892. * compare, and return a negative number, zero, or a positive number
  893. * depending on whether the first argument is less than, equal to, or
  894. * greater than the second.
  895. * @return {number} Lowest index of the target value if found, otherwise
  896. * (-(insertion point) - 1). The insertion point is where the value should
  897. * be inserted into arr to preserve the sorted property. Return value >= 0
  898. * iff target is found.
  899. * @template TARGET, VALUE
  900. */
  901. goog.array.binarySearch = function(arr, target, opt_compareFn) {
  902. return goog.array.binarySearch_(
  903. arr, opt_compareFn || goog.array.defaultCompare, false /* isEvaluator */,
  904. target);
  905. };
  906. /**
  907. * Selects an index in the specified array using the binary search algorithm.
  908. * The evaluator receives an element and determines whether the desired index
  909. * is before, at, or after it. The evaluator must be consistent (formally,
  910. * goog.array.map(goog.array.map(arr, evaluator, opt_obj), goog.math.sign)
  911. * must be monotonically non-increasing).
  912. *
  913. * Runtime: O(log n)
  914. *
  915. * @param {IArrayLike<VALUE>} arr The array to be searched.
  916. * @param {function(this:THIS, VALUE, number, ?): number} evaluator
  917. * Evaluator function that receives 3 arguments (the element, the index and
  918. * the array). Should return a negative number, zero, or a positive number
  919. * depending on whether the desired index is before, at, or after the
  920. * element passed to it.
  921. * @param {THIS=} opt_obj The object to be used as the value of 'this'
  922. * within evaluator.
  923. * @return {number} Index of the leftmost element matched by the evaluator, if
  924. * such exists; otherwise (-(insertion point) - 1). The insertion point is
  925. * the index of the first element for which the evaluator returns negative,
  926. * or arr.length if no such element exists. The return value is non-negative
  927. * iff a match is found.
  928. * @template THIS, VALUE
  929. */
  930. goog.array.binarySelect = function(arr, evaluator, opt_obj) {
  931. return goog.array.binarySearch_(
  932. arr, evaluator, true /* isEvaluator */, undefined /* opt_target */,
  933. opt_obj);
  934. };
  935. /**
  936. * Implementation of a binary search algorithm which knows how to use both
  937. * comparison functions and evaluators. If an evaluator is provided, will call
  938. * the evaluator with the given optional data object, conforming to the
  939. * interface defined in binarySelect. Otherwise, if a comparison function is
  940. * provided, will call the comparison function against the given data object.
  941. *
  942. * This implementation purposefully does not use goog.bind or goog.partial for
  943. * performance reasons.
  944. *
  945. * Runtime: O(log n)
  946. *
  947. * @param {IArrayLike<?>} arr The array to be searched.
  948. * @param {function(?, ?, ?): number | function(?, ?): number} compareFn
  949. * Either an evaluator or a comparison function, as defined by binarySearch
  950. * and binarySelect above.
  951. * @param {boolean} isEvaluator Whether the function is an evaluator or a
  952. * comparison function.
  953. * @param {?=} opt_target If the function is a comparison function, then
  954. * this is the target to binary search for.
  955. * @param {Object=} opt_selfObj If the function is an evaluator, this is an
  956. * optional this object for the evaluator.
  957. * @return {number} Lowest index of the target value if found, otherwise
  958. * (-(insertion point) - 1). The insertion point is where the value should
  959. * be inserted into arr to preserve the sorted property. Return value >= 0
  960. * iff target is found.
  961. * @private
  962. */
  963. goog.array.binarySearch_ = function(
  964. arr, compareFn, isEvaluator, opt_target, opt_selfObj) {
  965. var left = 0; // inclusive
  966. var right = arr.length; // exclusive
  967. var found;
  968. while (left < right) {
  969. var middle = (left + right) >> 1;
  970. var compareResult;
  971. if (isEvaluator) {
  972. compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);
  973. } else {
  974. // NOTE(dimvar): To avoid this cast, we'd have to use function overloading
  975. // for the type of binarySearch_, which the type system can't express yet.
  976. compareResult = /** @type {function(?, ?): number} */ (compareFn)(
  977. opt_target, arr[middle]);
  978. }
  979. if (compareResult > 0) {
  980. left = middle + 1;
  981. } else {
  982. right = middle;
  983. // We are looking for the lowest index so we can't return immediately.
  984. found = !compareResult;
  985. }
  986. }
  987. // left is the index if found, or the insertion point otherwise.
  988. // ~left is a shorthand for -left - 1.
  989. return found ? left : ~left;
  990. };
  991. /**
  992. * Sorts the specified array into ascending order. If no opt_compareFn is
  993. * specified, elements are compared using
  994. * <code>goog.array.defaultCompare</code>, which compares the elements using
  995. * the built in < and > operators. This will produce the expected behavior
  996. * for homogeneous arrays of String(s) and Number(s), unlike the native sort,
  997. * but will give unpredictable results for heterogeneous lists of strings and
  998. * numbers with different numbers of digits.
  999. *
  1000. * This sort is not guaranteed to be stable.
  1001. *
  1002. * Runtime: Same as <code>Array.prototype.sort</code>
  1003. *
  1004. * @param {Array<T>} arr The array to be sorted.
  1005. * @param {?function(T,T):number=} opt_compareFn Optional comparison
  1006. * function by which the
  1007. * array is to be ordered. Should take 2 arguments to compare, and return a
  1008. * negative number, zero, or a positive number depending on whether the
  1009. * first argument is less than, equal to, or greater than the second.
  1010. * @template T
  1011. */
  1012. goog.array.sort = function(arr, opt_compareFn) {
  1013. // TODO(arv): Update type annotation since null is not accepted.
  1014. arr.sort(opt_compareFn || goog.array.defaultCompare);
  1015. };
  1016. /**
  1017. * Sorts the specified array into ascending order in a stable way. If no
  1018. * opt_compareFn is specified, elements are compared using
  1019. * <code>goog.array.defaultCompare</code>, which compares the elements using
  1020. * the built in < and > operators. This will produce the expected behavior
  1021. * for homogeneous arrays of String(s) and Number(s).
  1022. *
  1023. * Runtime: Same as <code>Array.prototype.sort</code>, plus an additional
  1024. * O(n) overhead of copying the array twice.
  1025. *
  1026. * @param {Array<T>} arr The array to be sorted.
  1027. * @param {?function(T, T): number=} opt_compareFn Optional comparison function
  1028. * by which the array is to be ordered. Should take 2 arguments to compare,
  1029. * and return a negative number, zero, or a positive number depending on
  1030. * whether the first argument is less than, equal to, or greater than the
  1031. * second.
  1032. * @template T
  1033. */
  1034. goog.array.stableSort = function(arr, opt_compareFn) {
  1035. var compArr = new Array(arr.length);
  1036. for (var i = 0; i < arr.length; i++) {
  1037. compArr[i] = {index: i, value: arr[i]};
  1038. }
  1039. var valueCompareFn = opt_compareFn || goog.array.defaultCompare;
  1040. function stableCompareFn(obj1, obj2) {
  1041. return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;
  1042. }
  1043. goog.array.sort(compArr, stableCompareFn);
  1044. for (var i = 0; i < arr.length; i++) {
  1045. arr[i] = compArr[i].value;
  1046. }
  1047. };
  1048. /**
  1049. * Sort the specified array into ascending order based on item keys
  1050. * returned by the specified key function.
  1051. * If no opt_compareFn is specified, the keys are compared in ascending order
  1052. * using <code>goog.array.defaultCompare</code>.
  1053. *
  1054. * Runtime: O(S(f(n)), where S is runtime of <code>goog.array.sort</code>
  1055. * and f(n) is runtime of the key function.
  1056. *
  1057. * @param {Array<T>} arr The array to be sorted.
  1058. * @param {function(T): K} keyFn Function taking array element and returning
  1059. * a key used for sorting this element.
  1060. * @param {?function(K, K): number=} opt_compareFn Optional comparison function
  1061. * by which the keys are to be ordered. Should take 2 arguments to compare,
  1062. * and return a negative number, zero, or a positive number depending on
  1063. * whether the first argument is less than, equal to, or greater than the
  1064. * second.
  1065. * @template T,K
  1066. */
  1067. goog.array.sortByKey = function(arr, keyFn, opt_compareFn) {
  1068. var keyCompareFn = opt_compareFn || goog.array.defaultCompare;
  1069. goog.array.sort(
  1070. arr, function(a, b) { return keyCompareFn(keyFn(a), keyFn(b)); });
  1071. };
  1072. /**
  1073. * Sorts an array of objects by the specified object key and compare
  1074. * function. If no compare function is provided, the key values are
  1075. * compared in ascending order using <code>goog.array.defaultCompare</code>.
  1076. * This won't work for keys that get renamed by the compiler. So use
  1077. * {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.
  1078. * @param {Array<Object>} arr An array of objects to sort.
  1079. * @param {string} key The object key to sort by.
  1080. * @param {Function=} opt_compareFn The function to use to compare key
  1081. * values.
  1082. */
  1083. goog.array.sortObjectsByKey = function(arr, key, opt_compareFn) {
  1084. goog.array.sortByKey(arr, function(obj) { return obj[key]; }, opt_compareFn);
  1085. };
  1086. /**
  1087. * Tells if the array is sorted.
  1088. * @param {!Array<T>} arr The array.
  1089. * @param {?function(T,T):number=} opt_compareFn Function to compare the
  1090. * array elements.
  1091. * Should take 2 arguments to compare, and return a negative number, zero,
  1092. * or a positive number depending on whether the first argument is less
  1093. * than, equal to, or greater than the second.
  1094. * @param {boolean=} opt_strict If true no equal elements are allowed.
  1095. * @return {boolean} Whether the array is sorted.
  1096. * @template T
  1097. */
  1098. goog.array.isSorted = function(arr, opt_compareFn, opt_strict) {
  1099. var compare = opt_compareFn || goog.array.defaultCompare;
  1100. for (var i = 1; i < arr.length; i++) {
  1101. var compareResult = compare(arr[i - 1], arr[i]);
  1102. if (compareResult > 0 || compareResult == 0 && opt_strict) {
  1103. return false;
  1104. }
  1105. }
  1106. return true;
  1107. };
  1108. /**
  1109. * Compares two arrays for equality. Two arrays are considered equal if they
  1110. * have the same length and their corresponding elements are equal according to
  1111. * the comparison function.
  1112. *
  1113. * @param {IArrayLike<?>} arr1 The first array to compare.
  1114. * @param {IArrayLike<?>} arr2 The second array to compare.
  1115. * @param {Function=} opt_equalsFn Optional comparison function.
  1116. * Should take 2 arguments to compare, and return true if the arguments
  1117. * are equal. Defaults to {@link goog.array.defaultCompareEquality} which
  1118. * compares the elements using the built-in '===' operator.
  1119. * @return {boolean} Whether the two arrays are equal.
  1120. */
  1121. goog.array.equals = function(arr1, arr2, opt_equalsFn) {
  1122. if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||
  1123. arr1.length != arr2.length) {
  1124. return false;
  1125. }
  1126. var l = arr1.length;
  1127. var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality;
  1128. for (var i = 0; i < l; i++) {
  1129. if (!equalsFn(arr1[i], arr2[i])) {
  1130. return false;
  1131. }
  1132. }
  1133. return true;
  1134. };
  1135. /**
  1136. * 3-way array compare function.
  1137. * @param {!IArrayLike<VALUE>} arr1 The first array to
  1138. * compare.
  1139. * @param {!IArrayLike<VALUE>} arr2 The second array to
  1140. * compare.
  1141. * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
  1142. * function by which the array is to be ordered. Should take 2 arguments to
  1143. * compare, and return a negative number, zero, or a positive number
  1144. * depending on whether the first argument is less than, equal to, or
  1145. * greater than the second.
  1146. * @return {number} Negative number, zero, or a positive number depending on
  1147. * whether the first argument is less than, equal to, or greater than the
  1148. * second.
  1149. * @template VALUE
  1150. */
  1151. goog.array.compare3 = function(arr1, arr2, opt_compareFn) {
  1152. var compare = opt_compareFn || goog.array.defaultCompare;
  1153. var l = Math.min(arr1.length, arr2.length);
  1154. for (var i = 0; i < l; i++) {
  1155. var result = compare(arr1[i], arr2[i]);
  1156. if (result != 0) {
  1157. return result;
  1158. }
  1159. }
  1160. return goog.array.defaultCompare(arr1.length, arr2.length);
  1161. };
  1162. /**
  1163. * Compares its two arguments for order, using the built in < and >
  1164. * operators.
  1165. * @param {VALUE} a The first object to be compared.
  1166. * @param {VALUE} b The second object to be compared.
  1167. * @return {number} A negative number, zero, or a positive number as the first
  1168. * argument is less than, equal to, or greater than the second,
  1169. * respectively.
  1170. * @template VALUE
  1171. */
  1172. goog.array.defaultCompare = function(a, b) {
  1173. return a > b ? 1 : a < b ? -1 : 0;
  1174. };
  1175. /**
  1176. * Compares its two arguments for inverse order, using the built in < and >
  1177. * operators.
  1178. * @param {VALUE} a The first object to be compared.
  1179. * @param {VALUE} b The second object to be compared.
  1180. * @return {number} A negative number, zero, or a positive number as the first
  1181. * argument is greater than, equal to, or less than the second,
  1182. * respectively.
  1183. * @template VALUE
  1184. */
  1185. goog.array.inverseDefaultCompare = function(a, b) {
  1186. return -goog.array.defaultCompare(a, b);
  1187. };
  1188. /**
  1189. * Compares its two arguments for equality, using the built in === operator.
  1190. * @param {*} a The first object to compare.
  1191. * @param {*} b The second object to compare.
  1192. * @return {boolean} True if the two arguments are equal, false otherwise.
  1193. */
  1194. goog.array.defaultCompareEquality = function(a, b) {
  1195. return a === b;
  1196. };
  1197. /**
  1198. * Inserts a value into a sorted array. The array is not modified if the
  1199. * value is already present.
  1200. * @param {IArrayLike<VALUE>} array The array to modify.
  1201. * @param {VALUE} value The object to insert.
  1202. * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
  1203. * function by which the array is ordered. Should take 2 arguments to
  1204. * compare, and return a negative number, zero, or a positive number
  1205. * depending on whether the first argument is less than, equal to, or
  1206. * greater than the second.
  1207. * @return {boolean} True if an element was inserted.
  1208. * @template VALUE
  1209. */
  1210. goog.array.binaryInsert = function(array, value, opt_compareFn) {
  1211. var index = goog.array.binarySearch(array, value, opt_compareFn);
  1212. if (index < 0) {
  1213. goog.array.insertAt(array, value, -(index + 1));
  1214. return true;
  1215. }
  1216. return false;
  1217. };
  1218. /**
  1219. * Removes a value from a sorted array.
  1220. * @param {!IArrayLike<VALUE>} array The array to modify.
  1221. * @param {VALUE} value The object to remove.
  1222. * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
  1223. * function by which the array is ordered. Should take 2 arguments to
  1224. * compare, and return a negative number, zero, or a positive number
  1225. * depending on whether the first argument is less than, equal to, or
  1226. * greater than the second.
  1227. * @return {boolean} True if an element was removed.
  1228. * @template VALUE
  1229. */
  1230. goog.array.binaryRemove = function(array, value, opt_compareFn) {
  1231. var index = goog.array.binarySearch(array, value, opt_compareFn);
  1232. return (index >= 0) ? goog.array.removeAt(array, index) : false;
  1233. };
  1234. /**
  1235. * Splits an array into disjoint buckets according to a splitting function.
  1236. * @param {Array<T>} array The array.
  1237. * @param {function(this:S, T,number,Array<T>):?} sorter Function to call for
  1238. * every element. This takes 3 arguments (the element, the index and the
  1239. * array) and must return a valid object key (a string, number, etc), or
  1240. * undefined, if that object should not be placed in a bucket.
  1241. * @param {S=} opt_obj The object to be used as the value of 'this' within
  1242. * sorter.
  1243. * @return {!Object} An object, with keys being all of the unique return values
  1244. * of sorter, and values being arrays containing the items for
  1245. * which the splitter returned that key.
  1246. * @template T,S
  1247. */
  1248. goog.array.bucket = function(array, sorter, opt_obj) {
  1249. var buckets = {};
  1250. for (var i = 0; i < array.length; i++) {
  1251. var value = array[i];
  1252. var key = sorter.call(/** @type {?} */ (opt_obj), value, i, array);
  1253. if (goog.isDef(key)) {
  1254. // Push the value to the right bucket, creating it if necessary.
  1255. var bucket = buckets[key] || (buckets[key] = []);
  1256. bucket.push(value);
  1257. }
  1258. }
  1259. return buckets;
  1260. };
  1261. /**
  1262. * Creates a new object built from the provided array and the key-generation
  1263. * function.
  1264. * @param {IArrayLike<T>} arr Array or array like object over
  1265. * which to iterate whose elements will be the values in the new object.
  1266. * @param {?function(this:S, T, number, ?) : string} keyFunc The function to
  1267. * call for every element. This function takes 3 arguments (the element, the
  1268. * index and the array) and should return a string that will be used as the
  1269. * key for the element in the new object. If the function returns the same
  1270. * key for more than one element, the value for that key is
  1271. * implementation-defined.
  1272. * @param {S=} opt_obj The object to be used as the value of 'this'
  1273. * within keyFunc.
  1274. * @return {!Object<T>} The new object.
  1275. * @template T,S
  1276. */
  1277. goog.array.toObject = function(arr, keyFunc, opt_obj) {
  1278. var ret = {};
  1279. goog.array.forEach(arr, function(element, index) {
  1280. ret[keyFunc.call(/** @type {?} */ (opt_obj), element, index, arr)] =
  1281. element;
  1282. });
  1283. return ret;
  1284. };
  1285. /**
  1286. * Creates a range of numbers in an arithmetic progression.
  1287. *
  1288. * Range takes 1, 2, or 3 arguments:
  1289. * <pre>
  1290. * range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]
  1291. * range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]
  1292. * range(-2, -5, -1) produces [-2, -3, -4]
  1293. * range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.
  1294. * </pre>
  1295. *
  1296. * @param {number} startOrEnd The starting value of the range if an end argument
  1297. * is provided. Otherwise, the start value is 0, and this is the end value.
  1298. * @param {number=} opt_end The optional end value of the range.
  1299. * @param {number=} opt_step The step size between range values. Defaults to 1
  1300. * if opt_step is undefined or 0.
  1301. * @return {!Array<number>} An array of numbers for the requested range. May be
  1302. * an empty array if adding the step would not converge toward the end
  1303. * value.
  1304. */
  1305. goog.array.range = function(startOrEnd, opt_end, opt_step) {
  1306. var array = [];
  1307. var start = 0;
  1308. var end = startOrEnd;
  1309. var step = opt_step || 1;
  1310. if (opt_end !== undefined) {
  1311. start = startOrEnd;
  1312. end = opt_end;
  1313. }
  1314. if (step * (end - start) < 0) {
  1315. // Sign mismatch: start + step will never reach the end value.
  1316. return [];
  1317. }
  1318. if (step > 0) {
  1319. for (var i = start; i < end; i += step) {
  1320. array.push(i);
  1321. }
  1322. } else {
  1323. for (var i = start; i > end; i += step) {
  1324. array.push(i);
  1325. }
  1326. }
  1327. return array;
  1328. };
  1329. /**
  1330. * Returns an array consisting of the given value repeated N times.
  1331. *
  1332. * @param {VALUE} value The value to repeat.
  1333. * @param {number} n The repeat count.
  1334. * @return {!Array<VALUE>} An array with the repeated value.
  1335. * @template VALUE
  1336. */
  1337. goog.array.repeat = function(value, n) {
  1338. var array = [];
  1339. for (var i = 0; i < n; i++) {
  1340. array[i] = value;
  1341. }
  1342. return array;
  1343. };
  1344. /**
  1345. * Returns an array consisting of every argument with all arrays
  1346. * expanded in-place recursively.
  1347. *
  1348. * @param {...*} var_args The values to flatten.
  1349. * @return {!Array<?>} An array containing the flattened values.
  1350. */
  1351. goog.array.flatten = function(var_args) {
  1352. var CHUNK_SIZE = 8192;
  1353. var result = [];
  1354. for (var i = 0; i < arguments.length; i++) {
  1355. var element = arguments[i];
  1356. if (goog.isArray(element)) {
  1357. for (var c = 0; c < element.length; c += CHUNK_SIZE) {
  1358. var chunk = goog.array.slice(element, c, c + CHUNK_SIZE);
  1359. var recurseResult = goog.array.flatten.apply(null, chunk);
  1360. for (var r = 0; r < recurseResult.length; r++) {
  1361. result.push(recurseResult[r]);
  1362. }
  1363. }
  1364. } else {
  1365. result.push(element);
  1366. }
  1367. }
  1368. return result;
  1369. };
  1370. /**
  1371. * Rotates an array in-place. After calling this method, the element at
  1372. * index i will be the element previously at index (i - n) %
  1373. * array.length, for all values of i between 0 and array.length - 1,
  1374. * inclusive.
  1375. *
  1376. * For example, suppose list comprises [t, a, n, k, s]. After invoking
  1377. * rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].
  1378. *
  1379. * @param {!Array<T>} array The array to rotate.
  1380. * @param {number} n The amount to rotate.
  1381. * @return {!Array<T>} The array.
  1382. * @template T
  1383. */
  1384. goog.array.rotate = function(array, n) {
  1385. goog.asserts.assert(array.length != null);
  1386. if (array.length) {
  1387. n %= array.length;
  1388. if (n > 0) {
  1389. Array.prototype.unshift.apply(array, array.splice(-n, n));
  1390. } else if (n < 0) {
  1391. Array.prototype.push.apply(array, array.splice(0, -n));
  1392. }
  1393. }
  1394. return array;
  1395. };
  1396. /**
  1397. * Moves one item of an array to a new position keeping the order of the rest
  1398. * of the items. Example use case: keeping a list of JavaScript objects
  1399. * synchronized with the corresponding list of DOM elements after one of the
  1400. * elements has been dragged to a new position.
  1401. * @param {!IArrayLike<?>} arr The array to modify.
  1402. * @param {number} fromIndex Index of the item to move between 0 and
  1403. * {@code arr.length - 1}.
  1404. * @param {number} toIndex Target index between 0 and {@code arr.length - 1}.
  1405. */
  1406. goog.array.moveItem = function(arr, fromIndex, toIndex) {
  1407. goog.asserts.assert(fromIndex >= 0 && fromIndex < arr.length);
  1408. goog.asserts.assert(toIndex >= 0 && toIndex < arr.length);
  1409. // Remove 1 item at fromIndex.
  1410. var removedItems = Array.prototype.splice.call(arr, fromIndex, 1);
  1411. // Insert the removed item at toIndex.
  1412. Array.prototype.splice.call(arr, toIndex, 0, removedItems[0]);
  1413. // We don't use goog.array.insertAt and goog.array.removeAt, because they're
  1414. // significantly slower than splice.
  1415. };
  1416. /**
  1417. * Creates a new array for which the element at position i is an array of the
  1418. * ith element of the provided arrays. The returned array will only be as long
  1419. * as the shortest array provided; additional values are ignored. For example,
  1420. * the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].
  1421. *
  1422. * This is similar to the zip() function in Python. See {@link
  1423. * http://docs.python.org/library/functions.html#zip}
  1424. *
  1425. * @param {...!IArrayLike<?>} var_args Arrays to be combined.
  1426. * @return {!Array<!Array<?>>} A new array of arrays created from
  1427. * provided arrays.
  1428. */
  1429. goog.array.zip = function(var_args) {
  1430. if (!arguments.length) {
  1431. return [];
  1432. }
  1433. var result = [];
  1434. var minLen = arguments[0].length;
  1435. for (var i = 1; i < arguments.length; i++) {
  1436. if (arguments[i].length < minLen) {
  1437. minLen = arguments[i].length;
  1438. }
  1439. }
  1440. for (var i = 0; i < minLen; i++) {
  1441. var value = [];
  1442. for (var j = 0; j < arguments.length; j++) {
  1443. value.push(arguments[j][i]);
  1444. }
  1445. result.push(value);
  1446. }
  1447. return result;
  1448. };
  1449. /**
  1450. * Shuffles the values in the specified array using the Fisher-Yates in-place
  1451. * shuffle (also known as the Knuth Shuffle). By default, calls Math.random()
  1452. * and so resets the state of that random number generator. Similarly, may reset
  1453. * the state of the any other specified random number generator.
  1454. *
  1455. * Runtime: O(n)
  1456. *
  1457. * @param {!Array<?>} arr The array to be shuffled.
  1458. * @param {function():number=} opt_randFn Optional random function to use for
  1459. * shuffling.
  1460. * Takes no arguments, and returns a random number on the interval [0, 1).
  1461. * Defaults to Math.random() using JavaScript's built-in Math library.
  1462. */
  1463. goog.array.shuffle = function(arr, opt_randFn) {
  1464. var randFn = opt_randFn || Math.random;
  1465. for (var i = arr.length - 1; i > 0; i--) {
  1466. // Choose a random array index in [0, i] (inclusive with i).
  1467. var j = Math.floor(randFn() * (i + 1));
  1468. var tmp = arr[i];
  1469. arr[i] = arr[j];
  1470. arr[j] = tmp;
  1471. }
  1472. };
  1473. /**
  1474. * Returns a new array of elements from arr, based on the indexes of elements
  1475. * provided by index_arr. For example, the result of index copying
  1476. * ['a', 'b', 'c'] with index_arr [1,0,0,2] is ['b', 'a', 'a', 'c'].
  1477. *
  1478. * @param {!Array<T>} arr The array to get a indexed copy from.
  1479. * @param {!Array<number>} index_arr An array of indexes to get from arr.
  1480. * @return {!Array<T>} A new array of elements from arr in index_arr order.
  1481. * @template T
  1482. */
  1483. goog.array.copyByIndex = function(arr, index_arr) {
  1484. var result = [];
  1485. goog.array.forEach(index_arr, function(index) { result.push(arr[index]); });
  1486. return result;
  1487. };
  1488. /**
  1489. * Maps each element of the input array into zero or more elements of the output
  1490. * array.
  1491. *
  1492. * @param {!IArrayLike<VALUE>|string} arr Array or array like object
  1493. * over which to iterate.
  1494. * @param {function(this:THIS, VALUE, number, ?): !Array<RESULT>} f The function
  1495. * to call for every element. This function takes 3 arguments (the element,
  1496. * the index and the array) and should return an array. The result will be
  1497. * used to extend a new array.
  1498. * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.
  1499. * @return {!Array<RESULT>} a new array with the concatenation of all arrays
  1500. * returned from f.
  1501. * @template THIS, VALUE, RESULT
  1502. */
  1503. goog.array.concatMap = function(arr, f, opt_obj) {
  1504. return goog.array.concat.apply([], goog.array.map(arr, f, opt_obj));
  1505. };