underscore.js 52 KB

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