underscore.js 57 KB

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