underscore-v1.8.3.js 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620
  1. // Underscore.js 1.8.3
  2. // http://underscorejs.org
  3. // (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  4. // Underscore may be freely distributed under the MIT license.
  5. (function() {
  6. // Baseline setup
  7. // --------------
  8. // Establish the root object, `window` (`self`) in the browser, `global`
  9. // on the server, or `this` in some virtual machines. We use `self`
  10. // instead of `window` for `WebWorker` support.
  11. var root = typeof self == 'object' && self.self === self && self ||
  12. typeof global == 'object' && global.global === global && global ||
  13. this;
  14. // Save the previous value of the `_` variable.
  15. var previousUnderscore = root._;
  16. // Save bytes in the minified (but not gzipped) version:
  17. var ArrayProto = Array.prototype, ObjProto = Object.prototype;
  18. // Create quick reference variables for speed access to core prototypes.
  19. var
  20. push = ArrayProto.push,
  21. slice = ArrayProto.slice,
  22. toString = ObjProto.toString,
  23. hasOwnProperty = ObjProto.hasOwnProperty;
  24. // All **ECMAScript 5** native function implementations that we hope to use
  25. // are declared here.
  26. var
  27. nativeIsArray = Array.isArray,
  28. nativeKeys = Object.keys,
  29. nativeCreate = Object.create;
  30. // Naked function reference for surrogate-prototype-swapping.
  31. var Ctor = function(){};
  32. // Create a safe reference to the Underscore object for use below.
  33. var _ = function(obj) {
  34. if (obj instanceof _) return obj;
  35. if (!(this instanceof _)) return new _(obj);
  36. this._wrapped = obj;
  37. };
  38. // Export the Underscore object for **Node.js**, with
  39. // backwards-compatibility for their old module API. If we're in
  40. // the browser, add `_` as a global object.
  41. // (`nodeType` is checked to ensure that `module`
  42. // and `exports` are not HTML elements.)
  43. if (typeof exports != 'undefined' && !exports.nodeType) {
  44. if (typeof module != 'undefined' && !module.nodeType && module.exports) {
  45. exports = module.exports = _;
  46. }
  47. exports._ = _;
  48. } else {
  49. root._ = _;
  50. }
  51. // Current version.
  52. _.VERSION = '1.8.3';
  53. // Internal function that returns an efficient (for current engines) version
  54. // of the passed-in callback, to be repeatedly applied in other Underscore
  55. // functions.
  56. var optimizeCb = function(func, context, argCount) {
  57. if (context === void 0) return func;
  58. switch (argCount == null ? 3 : argCount) {
  59. case 1: return function(value) {
  60. return func.call(context, value);
  61. };
  62. // The 2-parameter case has been omitted only because no current consumers
  63. // made use of it.
  64. case 3: return function(value, index, collection) {
  65. return func.call(context, value, index, collection);
  66. };
  67. case 4: return function(accumulator, value, index, collection) {
  68. return func.call(context, accumulator, value, index, collection);
  69. };
  70. }
  71. return function() {
  72. return func.apply(context, arguments);
  73. };
  74. };
  75. // A mostly-internal function to generate callbacks that can be applied
  76. // to each element in a collection, returning the desired result — either
  77. // `identity`, an arbitrary callback, a property matcher, or a property accessor.
  78. var cb = function(value, context, argCount) {
  79. if (value == null) return _.identity;
  80. if (_.isFunction(value)) return optimizeCb(value, context, argCount);
  81. if (_.isObject(value)) return _.matcher(value);
  82. return _.property(value);
  83. };
  84. _.iteratee = function(value, context) {
  85. return cb(value, context, Infinity);
  86. };
  87. // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
  88. // This accumulates the arguments passed into an array, after a given index.
  89. var restArgs = function(func, startIndex) {
  90. startIndex = startIndex == null ? func.length - 1 : +startIndex;
  91. return function() {
  92. var length = Math.max(arguments.length - startIndex, 0);
  93. var rest = Array(length);
  94. for (var index = 0; index < length; index++) {
  95. rest[index] = arguments[index + startIndex];
  96. }
  97. switch (startIndex) {
  98. case 0: return func.call(this, rest);
  99. case 1: return func.call(this, arguments[0], rest);
  100. case 2: return func.call(this, arguments[0], arguments[1], rest);
  101. }
  102. var args = Array(startIndex + 1);
  103. for (index = 0; index < startIndex; index++) {
  104. args[index] = arguments[index];
  105. }
  106. args[startIndex] = rest;
  107. return func.apply(this, args);
  108. };
  109. };
  110. // An internal function for creating a new object that inherits from another.
  111. var baseCreate = function(prototype) {
  112. if (!_.isObject(prototype)) return {};
  113. if (nativeCreate) return nativeCreate(prototype);
  114. Ctor.prototype = prototype;
  115. var result = new Ctor;
  116. Ctor.prototype = null;
  117. return result;
  118. };
  119. var property = function(key) {
  120. return function(obj) {
  121. return obj == null ? void 0 : obj[key];
  122. };
  123. };
  124. // Helper for collection methods to determine whether a collection
  125. // should be iterated as an array or as an object.
  126. // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
  127. // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
  128. var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
  129. var getLength = property('length');
  130. var isArrayLike = function(collection) {
  131. var length = getLength(collection);
  132. return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
  133. };
  134. // Collection Functions
  135. // --------------------
  136. // The cornerstone, an `each` implementation, aka `forEach`.
  137. // Handles raw objects in addition to array-likes. Treats all
  138. // sparse array-likes as if they were dense.
  139. _.each = _.forEach = function(obj, iteratee, context) {
  140. iteratee = optimizeCb(iteratee, context);
  141. var i, length;
  142. if (isArrayLike(obj)) {
  143. for (i = 0, length = obj.length; i < length; i++) {
  144. iteratee(obj[i], i, obj);
  145. }
  146. } else {
  147. var keys = _.keys(obj);
  148. for (i = 0, length = keys.length; i < length; i++) {
  149. iteratee(obj[keys[i]], keys[i], obj);
  150. }
  151. }
  152. return obj;
  153. };
  154. // Return the results of applying the iteratee to each element.
  155. _.map = _.collect = function(obj, iteratee, context) {
  156. iteratee = cb(iteratee, context);
  157. var keys = !isArrayLike(obj) && _.keys(obj),
  158. length = (keys || obj).length,
  159. results = Array(length);
  160. for (var index = 0; index < length; index++) {
  161. var currentKey = keys ? keys[index] : index;
  162. results[index] = iteratee(obj[currentKey], currentKey, obj);
  163. }
  164. return results;
  165. };
  166. // Create a reducing function iterating left or right.
  167. var createReduce = function(dir) {
  168. // Optimized iterator function as using arguments.length
  169. // in the main function will deoptimize the, see #1991.
  170. var reducer = function(obj, iteratee, memo, initial) {
  171. var keys = !isArrayLike(obj) && _.keys(obj),
  172. length = (keys || obj).length,
  173. index = dir > 0 ? 0 : length - 1;
  174. if (!initial) {
  175. memo = obj[keys ? keys[index] : index];
  176. index += dir;
  177. }
  178. for (; index >= 0 && index < length; index += dir) {
  179. var currentKey = keys ? keys[index] : index;
  180. memo = iteratee(memo, obj[currentKey], currentKey, obj);
  181. }
  182. return memo;
  183. };
  184. return function(obj, iteratee, memo, context) {
  185. var initial = arguments.length >= 3;
  186. return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
  187. };
  188. };
  189. // **Reduce** builds up a single result from a list of values, aka `inject`,
  190. // or `foldl`.
  191. _.reduce = _.foldl = _.inject = createReduce(1);
  192. // The right-associative version of reduce, also known as `foldr`.
  193. _.reduceRight = _.foldr = createReduce(-1);
  194. // Return the first value which passes a truth test. Aliased as `detect`.
  195. _.find = _.detect = function(obj, predicate, context) {
  196. var key;
  197. if (isArrayLike(obj)) {
  198. key = _.findIndex(obj, predicate, context);
  199. } else {
  200. key = _.findKey(obj, predicate, context);
  201. }
  202. if (key !== void 0 && key !== -1) return obj[key];
  203. };
  204. // Return all the elements that pass a truth test.
  205. // Aliased as `select`.
  206. _.filter = _.select = function(obj, predicate, context) {
  207. var results = [];
  208. predicate = cb(predicate, context);
  209. _.each(obj, function(value, index, list) {
  210. if (predicate(value, index, list)) results.push(value);
  211. });
  212. return results;
  213. };
  214. // Return all the elements for which a truth test fails.
  215. _.reject = function(obj, predicate, context) {
  216. return _.filter(obj, _.negate(cb(predicate)), context);
  217. };
  218. // Determine whether all of the elements match a truth test.
  219. // Aliased as `all`.
  220. _.every = _.all = function(obj, predicate, context) {
  221. predicate = cb(predicate, context);
  222. var keys = !isArrayLike(obj) && _.keys(obj),
  223. length = (keys || obj).length;
  224. for (var index = 0; index < length; index++) {
  225. var currentKey = keys ? keys[index] : index;
  226. if (!predicate(obj[currentKey], currentKey, obj)) return false;
  227. }
  228. return true;
  229. };
  230. // Determine if at least one element in the object matches a truth test.
  231. // Aliased as `any`.
  232. _.some = _.any = function(obj, predicate, context) {
  233. predicate = cb(predicate, context);
  234. var keys = !isArrayLike(obj) && _.keys(obj),
  235. length = (keys || obj).length;
  236. for (var index = 0; index < length; index++) {
  237. var currentKey = keys ? keys[index] : index;
  238. if (predicate(obj[currentKey], currentKey, obj)) return true;
  239. }
  240. return false;
  241. };
  242. // Determine if the array or object contains a given item (using `===`).
  243. // Aliased as `includes` and `include`.
  244. _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
  245. if (!isArrayLike(obj)) obj = _.values(obj);
  246. if (typeof fromIndex != 'number' || guard) fromIndex = 0;
  247. return _.indexOf(obj, item, fromIndex) >= 0;
  248. };
  249. // Invoke a method (with arguments) on every item in a collection.
  250. _.invoke = restArgs(function(obj, method, args) {
  251. var isFunc = _.isFunction(method);
  252. return _.map(obj, function(value) {
  253. var func = isFunc ? method : value[method];
  254. return func == null ? func : func.apply(value, args);
  255. });
  256. });
  257. // Convenience version of a common use case of `map`: fetching a property.
  258. _.pluck = function(obj, key) {
  259. return _.map(obj, _.property(key));
  260. };
  261. // Convenience version of a common use case of `filter`: selecting only objects
  262. // containing specific `key:value` pairs.
  263. _.where = function(obj, attrs) {
  264. return _.filter(obj, _.matcher(attrs));
  265. };
  266. // Convenience version of a common use case of `find`: getting the first object
  267. // containing specific `key:value` pairs.
  268. _.findWhere = function(obj, attrs) {
  269. return _.find(obj, _.matcher(attrs));
  270. };
  271. // Return the maximum element (or element-based computation).
  272. _.max = function(obj, iteratee, context) {
  273. var result = -Infinity, lastComputed = -Infinity,
  274. value, computed;
  275. if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) {
  276. obj = isArrayLike(obj) ? obj : _.values(obj);
  277. for (var i = 0, length = obj.length; i < length; i++) {
  278. value = obj[i];
  279. if (value != null && value > result) {
  280. result = value;
  281. }
  282. }
  283. } else {
  284. iteratee = cb(iteratee, context);
  285. _.each(obj, function(v, index, list) {
  286. computed = iteratee(v, index, list);
  287. if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
  288. result = v;
  289. lastComputed = computed;
  290. }
  291. });
  292. }
  293. return result;
  294. };
  295. // Return the minimum element (or element-based computation).
  296. _.min = function(obj, iteratee, context) {
  297. var result = Infinity, lastComputed = Infinity,
  298. value, computed;
  299. if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) {
  300. obj = isArrayLike(obj) ? obj : _.values(obj);
  301. for (var i = 0, length = obj.length; i < length; i++) {
  302. value = obj[i];
  303. if (value != null && value < result) {
  304. result = value;
  305. }
  306. }
  307. } else {
  308. iteratee = cb(iteratee, context);
  309. _.each(obj, function(v, index, list) {
  310. computed = iteratee(v, index, list);
  311. if (computed < lastComputed || computed === Infinity && result === Infinity) {
  312. result = v;
  313. lastComputed = computed;
  314. }
  315. });
  316. }
  317. return result;
  318. };
  319. // Shuffle a collection.
  320. _.shuffle = function(obj) {
  321. return _.sample(obj, Infinity);
  322. };
  323. // Sample **n** random values from a collection using the modern version of the
  324. // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
  325. // If **n** is not specified, returns a single random element.
  326. // The internal `guard` argument allows it to work with `map`.
  327. _.sample = function(obj, n, guard) {
  328. if (n == null || guard) {
  329. if (!isArrayLike(obj)) obj = _.values(obj);
  330. return obj[_.random(obj.length - 1)];
  331. }
  332. var sample = isArrayLike(obj) ? _.clone(obj) : _.values(obj);
  333. var length = getLength(sample);
  334. n = Math.max(Math.min(n, length), 0);
  335. var last = length - 1;
  336. for (var index = 0; index < n; index++) {
  337. var rand = _.random(index, last);
  338. var temp = sample[index];
  339. sample[index] = sample[rand];
  340. sample[rand] = temp;
  341. }
  342. return sample.slice(0, n);
  343. };
  344. // Sort the object's values by a criterion produced by an iteratee.
  345. _.sortBy = function(obj, iteratee, context) {
  346. var index = 0;
  347. iteratee = cb(iteratee, context);
  348. return _.pluck(_.map(obj, function(value, key, list) {
  349. return {
  350. value: value,
  351. index: index++,
  352. criteria: iteratee(value, key, list)
  353. };
  354. }).sort(function(left, right) {
  355. var a = left.criteria;
  356. var b = right.criteria;
  357. if (a !== b) {
  358. if (a > b || a === void 0) return 1;
  359. if (a < b || b === void 0) return -1;
  360. }
  361. return left.index - right.index;
  362. }), 'value');
  363. };
  364. // An internal function used for aggregate "group by" operations.
  365. var group = function(behavior, partition) {
  366. return function(obj, iteratee, context) {
  367. var result = partition ? [[], []] : {};
  368. iteratee = cb(iteratee, context);
  369. _.each(obj, function(value, index) {
  370. var key = iteratee(value, index, obj);
  371. behavior(result, value, key);
  372. });
  373. return result;
  374. };
  375. };
  376. // Groups the object's values by a criterion. Pass either a string attribute
  377. // to group by, or a function that returns the criterion.
  378. _.groupBy = group(function(result, value, key) {
  379. if (_.has(result, key)) result[key].push(value); else result[key] = [value];
  380. });
  381. // Indexes the object's values by a criterion, similar to `groupBy`, but for
  382. // when you know that your index values will be unique.
  383. _.indexBy = group(function(result, value, key) {
  384. result[key] = value;
  385. });
  386. // Counts instances of an object that group by a certain criterion. Pass
  387. // either a string attribute to count by, or a function that returns the
  388. // criterion.
  389. _.countBy = group(function(result, value, key) {
  390. if (_.has(result, key)) result[key]++; else result[key] = 1;
  391. });
  392. var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
  393. // Safely create a real, live array from anything iterable.
  394. _.toArray = function(obj) {
  395. if (!obj) return [];
  396. if (_.isArray(obj)) return slice.call(obj);
  397. if (_.isString(obj)) {
  398. // Keep surrogate pair characters together
  399. return obj.match(reStrSymbol);
  400. }
  401. if (isArrayLike(obj)) return _.map(obj, _.identity);
  402. return _.values(obj);
  403. };
  404. // Return the number of elements in an object.
  405. _.size = function(obj) {
  406. if (obj == null) return 0;
  407. return isArrayLike(obj) ? obj.length : _.keys(obj).length;
  408. };
  409. // Split a collection into two arrays: one whose elements all satisfy the given
  410. // predicate, and one whose elements all do not satisfy the predicate.
  411. _.partition = group(function(result, value, pass) {
  412. result[pass ? 0 : 1].push(value);
  413. }, true);
  414. // Array Functions
  415. // ---------------
  416. // Get the first element of an array. Passing **n** will return the first N
  417. // values in the array. Aliased as `head` and `take`. The **guard** check
  418. // allows it to work with `_.map`.
  419. _.first = _.head = _.take = function(array, n, guard) {
  420. if (array == null) return void 0;
  421. if (n == null || guard) return array[0];
  422. return _.initial(array, array.length - n);
  423. };
  424. // Returns everything but the last entry of the array. Especially useful on
  425. // the arguments object. Passing **n** will return all the values in
  426. // the array, excluding the last N.
  427. _.initial = function(array, n, guard) {
  428. return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
  429. };
  430. // Get the last element of an array. Passing **n** will return the last N
  431. // values in the array.
  432. _.last = function(array, n, guard) {
  433. if (array == null) return void 0;
  434. if (n == null || guard) return array[array.length - 1];
  435. return _.rest(array, Math.max(0, array.length - n));
  436. };
  437. // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
  438. // Especially useful on the arguments object. Passing an **n** will return
  439. // the rest N values in the array.
  440. _.rest = _.tail = _.drop = function(array, n, guard) {
  441. return slice.call(array, n == null || guard ? 1 : n);
  442. };
  443. // Trim out all falsy values from an array.
  444. _.compact = function(array) {
  445. return _.filter(array, _.identity);
  446. };
  447. // Internal implementation of a recursive `flatten` function.
  448. var flatten = function(input, shallow, strict, output) {
  449. output = output || [];
  450. var idx = output.length;
  451. for (var i = 0, length = getLength(input); i < length; i++) {
  452. var value = input[i];
  453. if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
  454. // Flatten current level of array or arguments object
  455. if (shallow) {
  456. var j = 0, len = value.length;
  457. while (j < len) output[idx++] = value[j++];
  458. } else {
  459. flatten(value, shallow, strict, output);
  460. idx = output.length;
  461. }
  462. } else if (!strict) {
  463. output[idx++] = value;
  464. }
  465. }
  466. return output;
  467. };
  468. // Flatten out an array, either recursively (by default), or just one level.
  469. _.flatten = function(array, shallow) {
  470. return flatten(array, shallow, false);
  471. };
  472. // Return a version of the array that does not contain the specified value(s).
  473. _.without = restArgs(function(array, otherArrays) {
  474. return _.difference(array, otherArrays);
  475. });
  476. // Produce a duplicate-free version of the array. If the array has already
  477. // been sorted, you have the option of using a faster algorithm.
  478. // Aliased as `unique`.
  479. _.uniq = _.unique = function(array, isSorted, iteratee, context) {
  480. if (!_.isBoolean(isSorted)) {
  481. context = iteratee;
  482. iteratee = isSorted;
  483. isSorted = false;
  484. }
  485. if (iteratee != null) iteratee = cb(iteratee, context);
  486. var result = [];
  487. var seen = [];
  488. for (var i = 0, length = getLength(array); i < length; i++) {
  489. var value = array[i],
  490. computed = iteratee ? iteratee(value, i, array) : value;
  491. if (isSorted) {
  492. if (!i || seen !== computed) result.push(value);
  493. seen = computed;
  494. } else if (iteratee) {
  495. if (!_.contains(seen, computed)) {
  496. seen.push(computed);
  497. result.push(value);
  498. }
  499. } else if (!_.contains(result, value)) {
  500. result.push(value);
  501. }
  502. }
  503. return result;
  504. };
  505. // Produce an array that contains the union: each distinct element from all of
  506. // the passed-in arrays.
  507. _.union = restArgs(function(arrays) {
  508. return _.uniq(flatten(arrays, true, true));
  509. });
  510. // Produce an array that contains every item shared between all the
  511. // passed-in arrays.
  512. _.intersection = function(array) {
  513. var result = [];
  514. var argsLength = arguments.length;
  515. for (var i = 0, length = getLength(array); i < length; i++) {
  516. var item = array[i];
  517. if (_.contains(result, item)) continue;
  518. var j;
  519. for (j = 1; j < argsLength; j++) {
  520. if (!_.contains(arguments[j], item)) break;
  521. }
  522. if (j === argsLength) result.push(item);
  523. }
  524. return result;
  525. };
  526. // Take the difference between one array and a number of other arrays.
  527. // Only the elements present in just the first array will remain.
  528. _.difference = restArgs(function(array, rest) {
  529. rest = flatten(rest, true, true);
  530. return _.filter(array, function(value){
  531. return !_.contains(rest, value);
  532. });
  533. });
  534. // Complement of _.zip. Unzip accepts an array of arrays and groups
  535. // each array's elements on shared indices
  536. _.unzip = function(array) {
  537. var length = array && _.max(array, getLength).length || 0;
  538. var result = Array(length);
  539. for (var index = 0; index < length; index++) {
  540. result[index] = _.pluck(array, index);
  541. }
  542. return result;
  543. };
  544. // Zip together multiple lists into a single array -- elements that share
  545. // an index go together.
  546. _.zip = restArgs(_.unzip);
  547. // Converts lists into objects. Pass either a single array of `[key, value]`
  548. // pairs, or two parallel arrays of the same length -- one of keys, and one of
  549. // the corresponding values.
  550. _.object = function(list, values) {
  551. var result = {};
  552. for (var i = 0, length = getLength(list); i < length; i++) {
  553. if (values) {
  554. result[list[i]] = values[i];
  555. } else {
  556. result[list[i][0]] = list[i][1];
  557. }
  558. }
  559. return result;
  560. };
  561. // Generator function to create the findIndex and findLastIndex functions
  562. var createPredicateIndexFinder = function(dir) {
  563. return function(array, predicate, context) {
  564. predicate = cb(predicate, context);
  565. var length = getLength(array);
  566. var index = dir > 0 ? 0 : length - 1;
  567. for (; index >= 0 && index < length; index += dir) {
  568. if (predicate(array[index], index, array)) return index;
  569. }
  570. return -1;
  571. };
  572. };
  573. // Returns the first index on an array-like that passes a predicate test
  574. _.findIndex = createPredicateIndexFinder(1);
  575. _.findLastIndex = createPredicateIndexFinder(-1);
  576. // Use a comparator function to figure out the smallest index at which
  577. // an object should be inserted so as to maintain order. Uses binary search.
  578. _.sortedIndex = function(array, obj, iteratee, context) {
  579. iteratee = cb(iteratee, context, 1);
  580. var value = iteratee(obj);
  581. var low = 0, high = getLength(array);
  582. while (low < high) {
  583. var mid = Math.floor((low + high) / 2);
  584. if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
  585. }
  586. return low;
  587. };
  588. // Generator function to create the indexOf and lastIndexOf functions
  589. var createIndexFinder = function(dir, predicateFind, sortedIndex) {
  590. return function(array, item, idx) {
  591. var i = 0, length = getLength(array);
  592. if (typeof idx == 'number') {
  593. if (dir > 0) {
  594. i = idx >= 0 ? idx : Math.max(idx + length, i);
  595. } else {
  596. length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
  597. }
  598. } else if (sortedIndex && idx && length) {
  599. idx = sortedIndex(array, item);
  600. return array[idx] === item ? idx : -1;
  601. }
  602. if (item !== item) {
  603. idx = predicateFind(slice.call(array, i, length), _.isNaN);
  604. return idx >= 0 ? idx + i : -1;
  605. }
  606. for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
  607. if (array[idx] === item) return idx;
  608. }
  609. return -1;
  610. };
  611. };
  612. // Return the position of the first occurrence of an item in an array,
  613. // or -1 if the item is not included in the array.
  614. // If the array is large and already in sort order, pass `true`
  615. // for **isSorted** to use binary search.
  616. _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
  617. _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
  618. // Generate an integer Array containing an arithmetic progression. A port of
  619. // the native Python `range()` function. See
  620. // [the Python documentation](http://docs.python.org/library/functions.html#range).
  621. _.range = function(start, stop, step) {
  622. if (stop == null) {
  623. stop = start || 0;
  624. start = 0;
  625. }
  626. step = step || 1;
  627. var length = Math.max(Math.ceil((stop - start) / step), 0);
  628. var range = Array(length);
  629. for (var idx = 0; idx < length; idx++, start += step) {
  630. range[idx] = start;
  631. }
  632. return range;
  633. };
  634. // Split an **array** into several arrays containing **count** or less elements
  635. // of initial array
  636. _.chunk = function(array, count) {
  637. if (count == null || count < 1) return [];
  638. var result = [];
  639. var i = 0, length = array.length;
  640. while (i < length) {
  641. result.push(slice.call(array, i, i += count));
  642. }
  643. return result;
  644. };
  645. // Function (ahem) Functions
  646. // ------------------
  647. // Determines whether to execute a function as a constructor
  648. // or a normal function with the provided arguments
  649. var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
  650. if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
  651. var self = baseCreate(sourceFunc.prototype);
  652. var result = sourceFunc.apply(self, args);
  653. if (_.isObject(result)) return result;
  654. return self;
  655. };
  656. // Create a function bound to a given object (assigning `this`, and arguments,
  657. // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
  658. // available.
  659. _.bind = restArgs(function(func, context, args) {
  660. if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
  661. var bound = restArgs(function(callArgs) {
  662. return executeBound(func, bound, context, this, args.concat(callArgs));
  663. });
  664. return bound;
  665. });
  666. // Partially apply a function by creating a version that has had some of its
  667. // arguments pre-filled, without changing its dynamic `this` context. _ acts
  668. // as a placeholder by default, allowing any combination of arguments to be
  669. // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument.
  670. _.partial = restArgs(function(func, boundArgs) {
  671. var placeholder = _.partial.placeholder;
  672. var bound = function() {
  673. var position = 0, length = boundArgs.length;
  674. var args = Array(length);
  675. for (var i = 0; i < length; i++) {
  676. args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
  677. }
  678. while (position < arguments.length) args.push(arguments[position++]);
  679. return executeBound(func, bound, this, this, args);
  680. };
  681. return bound;
  682. });
  683. _.partial.placeholder = _;
  684. // Bind a number of an object's methods to that object. Remaining arguments
  685. // are the method names to be bound. Useful for ensuring that all callbacks
  686. // defined on an object belong to it.
  687. _.bindAll = restArgs(function(obj, keys) {
  688. keys = flatten(keys, false, false);
  689. var index = keys.length;
  690. if (index < 1) throw new Error('bindAll must be passed function names');
  691. while (index--) {
  692. var key = keys[index];
  693. obj[key] = _.bind(obj[key], obj);
  694. }
  695. });
  696. // Memoize an expensive function by storing its results.
  697. _.memoize = function(func, hasher) {
  698. var memoize = function(key) {
  699. var cache = memoize.cache;
  700. var address = '' + (hasher ? hasher.apply(this, arguments) : key);
  701. if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
  702. return cache[address];
  703. };
  704. memoize.cache = {};
  705. return memoize;
  706. };
  707. // Delays a function for the given number of milliseconds, and then calls
  708. // it with the arguments supplied.
  709. _.delay = restArgs(function(func, wait, args) {
  710. return setTimeout(function() {
  711. return func.apply(null, args);
  712. }, wait);
  713. });
  714. // Defers a function, scheduling it to run after the current call stack has
  715. // cleared.
  716. _.defer = _.partial(_.delay, _, 1);
  717. // Returns a function, that, when invoked, will only be triggered at most once
  718. // during a given window of time. Normally, the throttled function will run
  719. // as much as it can, without ever going more than once per `wait` duration;
  720. // but if you'd like to disable the execution on the leading edge, pass
  721. // `{leading: false}`. To disable execution on the trailing edge, ditto.
  722. _.throttle = function(func, wait, options) {
  723. var timeout, context, args, result;
  724. var previous = 0;
  725. if (!options) options = {};
  726. var later = function() {
  727. previous = options.leading === false ? 0 : _.now();
  728. timeout = null;
  729. result = func.apply(context, args);
  730. if (!timeout) context = args = null;
  731. };
  732. var throttled = function() {
  733. var now = _.now();
  734. if (!previous && options.leading === false) previous = now;
  735. var remaining = wait - (now - previous);
  736. context = this;
  737. args = arguments;
  738. if (remaining <= 0 || remaining > wait) {
  739. if (timeout) {
  740. clearTimeout(timeout);
  741. timeout = null;
  742. }
  743. previous = now;
  744. result = func.apply(context, args);
  745. if (!timeout) context = args = null;
  746. } else if (!timeout && options.trailing !== false) {
  747. timeout = setTimeout(later, remaining);
  748. }
  749. return result;
  750. };
  751. throttled.clear = function() {
  752. clearTimeout(timeout);
  753. previous = 0;
  754. timeout = context = args = null;
  755. };
  756. return throttled;
  757. };
  758. // Returns a function, that, as long as it continues to be invoked, will not
  759. // be triggered. The function will be called after it stops being called for
  760. // N milliseconds. If `immediate` is passed, trigger the function on the
  761. // leading edge, instead of the trailing.
  762. _.debounce = function(func, wait, immediate) {
  763. var timeout, result;
  764. var later = function(context, args) {
  765. timeout = null;
  766. if (args) result = func.apply(context, args);
  767. };
  768. var debounced = restArgs(function(args) {
  769. var callNow = immediate && !timeout;
  770. if (timeout) clearTimeout(timeout);
  771. if (callNow) {
  772. timeout = setTimeout(later, wait);
  773. result = func.apply(this, args);
  774. } else if (!immediate) {
  775. timeout = _.delay(later, wait, this, args);
  776. }
  777. return result;
  778. });
  779. debounced.clear = function() {
  780. clearTimeout(timeout);
  781. timeout = null;
  782. };
  783. return debounced;
  784. };
  785. // Returns the first function passed as an argument to the second,
  786. // allowing you to adjust arguments, run code before and after, and
  787. // conditionally execute the original function.
  788. _.wrap = function(func, wrapper) {
  789. return _.partial(wrapper, func);
  790. };
  791. // Returns a negated version of the passed-in predicate.
  792. _.negate = function(predicate) {
  793. return function() {
  794. return !predicate.apply(this, arguments);
  795. };
  796. };
  797. // Returns a function that is the composition of a list of functions, each
  798. // consuming the return value of the function that follows.
  799. _.compose = function() {
  800. var args = arguments;
  801. var start = args.length - 1;
  802. return function() {
  803. var i = start;
  804. var result = args[start].apply(this, arguments);
  805. while (i--) result = args[i].call(this, result);
  806. return result;
  807. };
  808. };
  809. // Returns a function that will only be executed on and after the Nth call.
  810. _.after = function(times, func) {
  811. return function() {
  812. if (--times < 1) {
  813. return func.apply(this, arguments);
  814. }
  815. };
  816. };
  817. // Returns a function that will only be executed up to (but not including) the Nth call.
  818. _.before = function(times, func) {
  819. var memo;
  820. return function() {
  821. if (--times > 0) {
  822. memo = func.apply(this, arguments);
  823. }
  824. if (times <= 1) func = null;
  825. return memo;
  826. };
  827. };
  828. // Returns a function that will be executed at most one time, no matter how
  829. // often you call it. Useful for lazy initialization.
  830. _.once = _.partial(_.before, 2);
  831. _.restArgs = restArgs;
  832. // Object Functions
  833. // ----------------
  834. // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
  835. var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
  836. var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
  837. 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
  838. var collectNonEnumProps = function(obj, keys) {
  839. var nonEnumIdx = nonEnumerableProps.length;
  840. var constructor = obj.constructor;
  841. var proto = _.isFunction(constructor) && constructor.prototype || ObjProto;
  842. // Constructor is a special case.
  843. var prop = 'constructor';
  844. if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
  845. while (nonEnumIdx--) {
  846. prop = nonEnumerableProps[nonEnumIdx];
  847. if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
  848. keys.push(prop);
  849. }
  850. }
  851. };
  852. // Retrieve the names of an object's own properties.
  853. // Delegates to **ECMAScript 5**'s native `Object.keys`
  854. _.keys = function(obj) {
  855. if (!_.isObject(obj)) return [];
  856. if (nativeKeys) return nativeKeys(obj);
  857. var keys = [];
  858. for (var key in obj) if (_.has(obj, key)) keys.push(key);
  859. // Ahem, IE < 9.
  860. if (hasEnumBug) collectNonEnumProps(obj, keys);
  861. return keys;
  862. };
  863. // Retrieve all the property names of an object.
  864. _.allKeys = function(obj) {
  865. if (!_.isObject(obj)) return [];
  866. var keys = [];
  867. for (var key in obj) keys.push(key);
  868. // Ahem, IE < 9.
  869. if (hasEnumBug) collectNonEnumProps(obj, keys);
  870. return keys;
  871. };
  872. // Retrieve the values of an object's properties.
  873. _.values = function(obj) {
  874. var keys = _.keys(obj);
  875. var length = keys.length;
  876. var values = Array(length);
  877. for (var i = 0; i < length; i++) {
  878. values[i] = obj[keys[i]];
  879. }
  880. return values;
  881. };
  882. // Returns the results of applying the iteratee to each element of the object
  883. // In contrast to _.map it returns an object
  884. _.mapObject = function(obj, iteratee, context) {
  885. iteratee = cb(iteratee, context);
  886. var keys = _.keys(obj),
  887. length = keys.length,
  888. results = {};
  889. for (var index = 0; index < length; index++) {
  890. var currentKey = keys[index];
  891. results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
  892. }
  893. return results;
  894. };
  895. // Convert an object into a list of `[key, value]` pairs.
  896. _.pairs = function(obj) {
  897. var keys = _.keys(obj);
  898. var length = keys.length;
  899. var pairs = Array(length);
  900. for (var i = 0; i < length; i++) {
  901. pairs[i] = [keys[i], obj[keys[i]]];
  902. }
  903. return pairs;
  904. };
  905. // Invert the keys and values of an object. The values must be serializable.
  906. _.invert = function(obj) {
  907. var result = {};
  908. var keys = _.keys(obj);
  909. for (var i = 0, length = keys.length; i < length; i++) {
  910. result[obj[keys[i]]] = keys[i];
  911. }
  912. return result;
  913. };
  914. // Return a sorted list of the function names available on the object.
  915. // Aliased as `methods`
  916. _.functions = _.methods = function(obj) {
  917. var names = [];
  918. for (var key in obj) {
  919. if (_.isFunction(obj[key])) names.push(key);
  920. }
  921. return names.sort();
  922. };
  923. // An internal function for creating assigner functions.
  924. var createAssigner = function(keysFunc, defaults) {
  925. return function(obj) {
  926. var length = arguments.length;
  927. if (defaults) obj = Object(obj);
  928. if (length < 2 || obj == null) return obj;
  929. for (var index = 1; index < length; index++) {
  930. var source = arguments[index],
  931. keys = keysFunc(source),
  932. l = keys.length;
  933. for (var i = 0; i < l; i++) {
  934. var key = keys[i];
  935. if (!defaults || obj[key] === void 0) obj[key] = source[key];
  936. }
  937. }
  938. return obj;
  939. };
  940. };
  941. // Extend a given object with all the properties in passed-in object(s).
  942. _.extend = createAssigner(_.allKeys);
  943. // Assigns a given object with all the own properties in the passed-in object(s)
  944. // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
  945. _.extendOwn = _.assign = createAssigner(_.keys);
  946. // Returns the first key on an object that passes a predicate test
  947. _.findKey = function(obj, predicate, context) {
  948. predicate = cb(predicate, context);
  949. var keys = _.keys(obj), key;
  950. for (var i = 0, length = keys.length; i < length; i++) {
  951. key = keys[i];
  952. if (predicate(obj[key], key, obj)) return key;
  953. }
  954. };
  955. // Internal pick helper function to determine if `obj` has key `key`.
  956. var keyInObj = function(value, key, obj) {
  957. return key in obj;
  958. };
  959. // Return a copy of the object only containing the whitelisted properties.
  960. _.pick = restArgs(function(obj, keys) {
  961. var result = {}, iteratee = keys[0];
  962. if (obj == null) return result;
  963. if (_.isFunction(iteratee)) {
  964. if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]);
  965. keys = _.allKeys(obj);
  966. } else {
  967. iteratee = keyInObj;
  968. keys = flatten(keys, false, false);
  969. obj = Object(obj);
  970. }
  971. for (var i = 0, length = keys.length; i < length; i++) {
  972. var key = keys[i];
  973. var value = obj[key];
  974. if (iteratee(value, key, obj)) result[key] = value;
  975. }
  976. return result;
  977. });
  978. // Return a copy of the object without the blacklisted properties.
  979. _.omit = restArgs(function(obj, keys) {
  980. var iteratee = keys[0], context;
  981. if (_.isFunction(iteratee)) {
  982. iteratee = _.negate(iteratee);
  983. if (keys.length > 1) context = keys[1];
  984. } else {
  985. keys = _.map(flatten(keys, false, false), String);
  986. iteratee = function(value, key) {
  987. return !_.contains(keys, key);
  988. };
  989. }
  990. return _.pick(obj, iteratee, context);
  991. });
  992. // Fill in a given object with default properties.
  993. _.defaults = createAssigner(_.allKeys, true);
  994. // Creates an object that inherits from the given prototype object.
  995. // If additional properties are provided then they will be added to the
  996. // created object.
  997. _.create = function(prototype, props) {
  998. var result = baseCreate(prototype);
  999. if (props) _.extendOwn(result, props);
  1000. return result;
  1001. };
  1002. // Create a (shallow-cloned) duplicate of an object.
  1003. _.clone = function(obj) {
  1004. if (!_.isObject(obj)) return obj;
  1005. return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  1006. };
  1007. // Invokes interceptor with the obj, and then returns obj.
  1008. // The primary purpose of this method is to "tap into" a method chain, in
  1009. // order to perform operations on intermediate results within the chain.
  1010. _.tap = function(obj, interceptor) {
  1011. interceptor(obj);
  1012. return obj;
  1013. };
  1014. // Returns whether an object has a given set of `key:value` pairs.
  1015. _.isMatch = function(object, attrs) {
  1016. var keys = _.keys(attrs), length = keys.length;
  1017. if (object == null) return !length;
  1018. var obj = Object(object);
  1019. for (var i = 0; i < length; i++) {
  1020. var key = keys[i];
  1021. if (attrs[key] !== obj[key] || !(key in obj)) return false;
  1022. }
  1023. return true;
  1024. };
  1025. // Internal recursive comparison function for `isEqual`.
  1026. var eq, deepEq;
  1027. eq = function(a, b, aStack, bStack) {
  1028. // Identical objects are equal. `0 === -0`, but they aren't identical.
  1029. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
  1030. if (a === b) return a !== 0 || 1 / a === 1 / b;
  1031. // A strict comparison is necessary because `null == undefined`.
  1032. if (a == null || b == null) return a === b;
  1033. // `NaN`s are equivalent, but non-reflexive.
  1034. if (a !== a) return b !== b;
  1035. // Exhaust primitive checks
  1036. var type = typeof a;
  1037. if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;
  1038. return deepEq(a, b, aStack, bStack);
  1039. };
  1040. // Internal recursive comparison function for `isEqual`.
  1041. deepEq = function(a, b, aStack, bStack) {
  1042. // Unwrap any wrapped objects.
  1043. if (a instanceof _) a = a._wrapped;
  1044. if (b instanceof _) b = b._wrapped;
  1045. // Compare `[[Class]]` names.
  1046. var className = toString.call(a);
  1047. if (className !== toString.call(b)) return false;
  1048. switch (className) {
  1049. // Strings, numbers, regular expressions, dates, and booleans are compared by value.
  1050. case '[object RegExp]':
  1051. // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
  1052. case '[object String]':
  1053. // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
  1054. // equivalent to `new String("5")`.
  1055. return '' + a === '' + b;
  1056. case '[object Number]':
  1057. // `NaN`s are equivalent, but non-reflexive.
  1058. // Object(NaN) is equivalent to NaN
  1059. if (+a !== +a) return +b !== +b;
  1060. // An `egal` comparison is performed for other numeric values.
  1061. return +a === 0 ? 1 / +a === 1 / b : +a === +b;
  1062. case '[object Date]':
  1063. case '[object Boolean]':
  1064. // Coerce dates and booleans to numeric primitive values. Dates are compared by their
  1065. // millisecond representations. Note that invalid dates with millisecond representations
  1066. // of `NaN` are not equivalent.
  1067. return +a === +b;
  1068. }
  1069. var areArrays = className === '[object Array]';
  1070. if (!areArrays) {
  1071. if (typeof a != 'object' || typeof b != 'object') return false;
  1072. // Objects with different constructors are not equivalent, but `Object`s or `Array`s
  1073. // from different frames are.
  1074. var aCtor = a.constructor, bCtor = b.constructor;
  1075. if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
  1076. _.isFunction(bCtor) && bCtor instanceof bCtor)
  1077. && ('constructor' in a && 'constructor' in b)) {
  1078. return false;
  1079. }
  1080. }
  1081. // Assume equality for cyclic structures. The algorithm for detecting cyclic
  1082. // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
  1083. // Initializing stack of traversed objects.
  1084. // It's done here since we only need them for objects and arrays comparison.
  1085. aStack = aStack || [];
  1086. bStack = bStack || [];
  1087. var length = aStack.length;
  1088. while (length--) {
  1089. // Linear search. Performance is inversely proportional to the number of
  1090. // unique nested structures.
  1091. if (aStack[length] === a) return bStack[length] === b;
  1092. }
  1093. // Add the first object to the stack of traversed objects.
  1094. aStack.push(a);
  1095. bStack.push(b);
  1096. // Recursively compare objects and arrays.
  1097. if (areArrays) {
  1098. // Compare array lengths to determine if a deep comparison is necessary.
  1099. length = a.length;
  1100. if (length !== b.length) return false;
  1101. // Deep compare the contents, ignoring non-numeric properties.
  1102. while (length--) {
  1103. if (!eq(a[length], b[length], aStack, bStack)) return false;
  1104. }
  1105. } else {
  1106. // Deep compare objects.
  1107. var keys = _.keys(a), key;
  1108. length = keys.length;
  1109. // Ensure that both objects contain the same number of properties before comparing deep equality.
  1110. if (_.keys(b).length !== length) return false;
  1111. while (length--) {
  1112. // Deep compare each member
  1113. key = keys[length];
  1114. if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
  1115. }
  1116. }
  1117. // Remove the first object from the stack of traversed objects.
  1118. aStack.pop();
  1119. bStack.pop();
  1120. return true;
  1121. };
  1122. // Perform a deep comparison to check if two objects are equal.
  1123. _.isEqual = function(a, b) {
  1124. return eq(a, b);
  1125. };
  1126. // Is a given array, string, or object empty?
  1127. // An "empty" object has no enumerable own-properties.
  1128. _.isEmpty = function(obj) {
  1129. if (obj == null) return true;
  1130. if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
  1131. return _.keys(obj).length === 0;
  1132. };
  1133. // Is a given value a DOM element?
  1134. _.isElement = function(obj) {
  1135. return !!(obj && obj.nodeType === 1);
  1136. };
  1137. // Is a given value an array?
  1138. // Delegates to ECMA5's native Array.isArray
  1139. _.isArray = nativeIsArray || function(obj) {
  1140. return toString.call(obj) === '[object Array]';
  1141. };
  1142. // Is a given variable an object?
  1143. _.isObject = function(obj) {
  1144. var type = typeof obj;
  1145. return type === 'function' || type === 'object' && !!obj;
  1146. };
  1147. // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
  1148. _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
  1149. _['is' + name] = function(obj) {
  1150. return toString.call(obj) === '[object ' + name + ']';
  1151. };
  1152. });
  1153. // Define a fallback version of the method in browsers (ahem, IE < 9), where
  1154. // there isn't any inspectable "Arguments" type.
  1155. if (!_.isArguments(arguments)) {
  1156. _.isArguments = function(obj) {
  1157. return _.has(obj, 'callee');
  1158. };
  1159. }
  1160. // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
  1161. // IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
  1162. var nodelist = root.document && root.document.childNodes;
  1163. if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
  1164. _.isFunction = function(obj) {
  1165. return typeof obj == 'function' || false;
  1166. };
  1167. }
  1168. // Is a given object a finite number?
  1169. _.isFinite = function(obj) {
  1170. return isFinite(obj) && !isNaN(parseFloat(obj));
  1171. };
  1172. // Is the given value `NaN`?
  1173. _.isNaN = function(obj) {
  1174. return _.isNumber(obj) && isNaN(obj);
  1175. };
  1176. // Is a given value a boolean?
  1177. _.isBoolean = function(obj) {
  1178. return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
  1179. };
  1180. // Is a given value equal to null?
  1181. _.isNull = function(obj) {
  1182. return obj === null;
  1183. };
  1184. // Is a given variable undefined?
  1185. _.isUndefined = function(obj) {
  1186. return obj === void 0;
  1187. };
  1188. // Shortcut function for checking if an object has a given property directly
  1189. // on itself (in other words, not on a prototype).
  1190. _.has = function(obj, key) {
  1191. return obj != null && hasOwnProperty.call(obj, key);
  1192. };
  1193. // Utility Functions
  1194. // -----------------
  1195. // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  1196. // previous owner. Returns a reference to the Underscore object.
  1197. _.noConflict = function() {
  1198. root._ = previousUnderscore;
  1199. return this;
  1200. };
  1201. // Keep the identity function around for default iteratees.
  1202. _.identity = function(value) {
  1203. return value;
  1204. };
  1205. // Predicate-generating functions. Often useful outside of Underscore.
  1206. _.constant = function(value) {
  1207. return function() {
  1208. return value;
  1209. };
  1210. };
  1211. _.noop = function(){};
  1212. _.property = property;
  1213. // Generates a function for a given object that returns a given property.
  1214. _.propertyOf = function(obj) {
  1215. return obj == null ? function(){} : function(key) {
  1216. return obj[key];
  1217. };
  1218. };
  1219. // Returns a predicate for checking whether an object has a given set of
  1220. // `key:value` pairs.
  1221. _.matcher = _.matches = function(attrs) {
  1222. attrs = _.extendOwn({}, attrs);
  1223. return function(obj) {
  1224. return _.isMatch(obj, attrs);
  1225. };
  1226. };
  1227. // Run a function **n** times.
  1228. _.times = function(n, iteratee, context) {
  1229. var accum = Array(Math.max(0, n));
  1230. iteratee = optimizeCb(iteratee, context, 1);
  1231. for (var i = 0; i < n; i++) accum[i] = iteratee(i);
  1232. return accum;
  1233. };
  1234. // Return a random integer between min and max (inclusive).
  1235. _.random = function(min, max) {
  1236. if (max == null) {
  1237. max = min;
  1238. min = 0;
  1239. }
  1240. return min + Math.floor(Math.random() * (max - min + 1));
  1241. };
  1242. // A (possibly faster) way to get the current timestamp as an integer.
  1243. _.now = Date.now || function() {
  1244. return new Date().getTime();
  1245. };
  1246. // List of HTML entities for escaping.
  1247. var escapeMap = {
  1248. '&': '&amp;',
  1249. '<': '&lt;',
  1250. '>': '&gt;',
  1251. '"': '&quot;',
  1252. "'": '&#x27;',
  1253. '`': '&#x60;'
  1254. };
  1255. var unescapeMap = _.invert(escapeMap);
  1256. // Functions for escaping and unescaping strings to/from HTML interpolation.
  1257. var createEscaper = function(map) {
  1258. var escaper = function(match) {
  1259. return map[match];
  1260. };
  1261. // Regexes for identifying a key that needs to be escaped
  1262. var source = '(?:' + _.keys(map).join('|') + ')';
  1263. var testRegexp = RegExp(source);
  1264. var replaceRegexp = RegExp(source, 'g');
  1265. return function(string) {
  1266. string = string == null ? '' : '' + string;
  1267. return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
  1268. };
  1269. };
  1270. _.escape = createEscaper(escapeMap);
  1271. _.unescape = createEscaper(unescapeMap);
  1272. // If the value of the named `property` is a function then invoke it with the
  1273. // `object` as context; otherwise, return it.
  1274. _.result = function(object, prop, fallback) {
  1275. var value = object == null ? void 0 : object[prop];
  1276. if (value === void 0) {
  1277. value = fallback;
  1278. }
  1279. return _.isFunction(value) ? value.call(object) : value;
  1280. };
  1281. // Generate a unique integer id (unique within the entire client session).
  1282. // Useful for temporary DOM ids.
  1283. var idCounter = 0;
  1284. _.uniqueId = function(prefix) {
  1285. var id = ++idCounter + '';
  1286. return prefix ? prefix + id : id;
  1287. };
  1288. // By default, Underscore uses ERB-style template delimiters, change the
  1289. // following template settings to use alternative delimiters.
  1290. _.templateSettings = {
  1291. evaluate: /<%([\s\S]+?)%>/g,
  1292. interpolate: /<%=([\s\S]+?)%>/g,
  1293. escape: /<%-([\s\S]+?)%>/g
  1294. };
  1295. // When customizing `templateSettings`, if you don't want to define an
  1296. // interpolation, evaluation or escaping regex, we need one that is
  1297. // guaranteed not to match.
  1298. var noMatch = /(.)^/;
  1299. // Certain characters need to be escaped so that they can be put into a
  1300. // string literal.
  1301. var escapes = {
  1302. "'": "'",
  1303. '\\': '\\',
  1304. '\r': 'r',
  1305. '\n': 'n',
  1306. '\u2028': 'u2028',
  1307. '\u2029': 'u2029'
  1308. };
  1309. var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
  1310. var escapeChar = function(match) {
  1311. return '\\' + escapes[match];
  1312. };
  1313. // JavaScript micro-templating, similar to John Resig's implementation.
  1314. // Underscore templating handles arbitrary delimiters, preserves whitespace,
  1315. // and correctly escapes quotes within interpolated code.
  1316. // NB: `oldSettings` only exists for backwards compatibility.
  1317. _.template = function(text, settings, oldSettings) {
  1318. if (!settings && oldSettings) settings = oldSettings;
  1319. settings = _.defaults({}, settings, _.templateSettings);
  1320. // Combine delimiters into one regular expression via alternation.
  1321. var matcher = RegExp([
  1322. (settings.escape || noMatch).source,
  1323. (settings.interpolate || noMatch).source,
  1324. (settings.evaluate || noMatch).source
  1325. ].join('|') + '|$', 'g');
  1326. // Compile the template source, escaping string literals appropriately.
  1327. var index = 0;
  1328. var source = "__p+='";
  1329. text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
  1330. source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
  1331. index = offset + match.length;
  1332. if (escape) {
  1333. source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
  1334. } else if (interpolate) {
  1335. source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
  1336. } else if (evaluate) {
  1337. source += "';\n" + evaluate + "\n__p+='";
  1338. }
  1339. // Adobe VMs need the match returned to produce the correct offset.
  1340. return match;
  1341. });
  1342. source += "';\n";
  1343. // If a variable is not specified, place data values in local scope.
  1344. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
  1345. source = "var __t,__p='',__j=Array.prototype.join," +
  1346. "print=function(){__p+=__j.call(arguments,'');};\n" +
  1347. source + 'return __p;\n';
  1348. var render;
  1349. try {
  1350. render = new Function(settings.variable || 'obj', '_', source);
  1351. } catch (e) {
  1352. e.source = source;
  1353. throw e;
  1354. }
  1355. var template = function(data) {
  1356. return render.call(this, data, _);
  1357. };
  1358. // Provide the compiled source as a convenience for precompilation.
  1359. var argument = settings.variable || 'obj';
  1360. template.source = 'function(' + argument + '){\n' + source + '}';
  1361. return template;
  1362. };
  1363. // Add a "chain" function. Start chaining a wrapped Underscore object.
  1364. _.chain = function(obj) {
  1365. var instance = _(obj);
  1366. instance._chain = true;
  1367. return instance;
  1368. };
  1369. // OOP
  1370. // ---------------
  1371. // If Underscore is called as a function, it returns a wrapped object that
  1372. // can be used OO-style. This wrapper holds altered versions of all the
  1373. // underscore functions. Wrapped objects may be chained.
  1374. // Helper function to continue chaining intermediate results.
  1375. var chainResult = function(instance, obj) {
  1376. return instance._chain ? _(obj).chain() : obj;
  1377. };
  1378. // Add your own custom functions to the Underscore object.
  1379. _.mixin = function(obj) {
  1380. _.each(_.functions(obj), function(name) {
  1381. var func = _[name] = obj[name];
  1382. _.prototype[name] = function() {
  1383. var args = [this._wrapped];
  1384. push.apply(args, arguments);
  1385. return chainResult(this, func.apply(_, args));
  1386. };
  1387. });
  1388. };
  1389. // Add all of the Underscore functions to the wrapper object.
  1390. _.mixin(_);
  1391. // Add all mutator Array functions to the wrapper.
  1392. _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
  1393. var method = ArrayProto[name];
  1394. _.prototype[name] = function() {
  1395. var obj = this._wrapped;
  1396. method.apply(obj, arguments);
  1397. if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
  1398. return chainResult(this, obj);
  1399. };
  1400. });
  1401. // Add all accessor Array functions to the wrapper.
  1402. _.each(['concat', 'join', 'slice'], function(name) {
  1403. var method = ArrayProto[name];
  1404. _.prototype[name] = function() {
  1405. return chainResult(this, method.apply(this._wrapped, arguments));
  1406. };
  1407. });
  1408. // Extracts the result from a wrapped and chained object.
  1409. _.prototype.value = function() {
  1410. return this._wrapped;
  1411. };
  1412. // Provide unwrapping proxy for some methods used in engine operations
  1413. // such as arithmetic and JSON stringification.
  1414. _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
  1415. _.prototype.toString = function() {
  1416. return '' + this._wrapped;
  1417. };
  1418. // AMD registration happens at the end for compatibility with AMD loaders
  1419. // that may not enforce next-turn semantics on modules. Even though general
  1420. // practice for AMD registration is to be anonymous, underscore registers
  1421. // as a named module because, like jQuery, it is a base library that is
  1422. // popular enough to be bundled in a third party lib, but not be part of
  1423. // an AMD load request. Those cases could generate an error when an
  1424. // anonymous define() is called outside of a loader request.
  1425. if (typeof define == 'function' && define.amd) {
  1426. define('underscore', [], function() {
  1427. return _;
  1428. });
  1429. }
  1430. }());