underscore.js 49 KB

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