Underscore.js 1.8.3

Underscore provides over 100 functions that support both your favorite workaday functional helpers

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/17419/109803/Underscorejs%20183.js

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