Underscore.js 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694
  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. window._ = _;
  1501. }());