underscore.js 57 KB

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