PageRenderTime 49ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/files/underscorejs/1.8.1/underscore.js

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