PageRenderTime 53ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/files/underscorejs/1.8.0/underscore.js

https://gitlab.com/Mirros/jsdelivr
JavaScript | 1472 lines | 1076 code | 145 blank | 251 comment | 303 complexity | 2ab3a0695336f2556d7c3918780d6295 MD5 | raw file
  1. // Underscore.js 1.8.0
  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. // Reusable constructor function for prototype setting.
  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.0';
  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. return function bound() {
  634. return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
  635. };
  636. };
  637. // Partially apply a function by creating a version that has had some of its
  638. // arguments pre-filled, without changing its dynamic `this` context. _ acts
  639. // as a placeholder, allowing any combination of arguments to be pre-filled.
  640. _.partial = function(func) {
  641. var boundArgs = slice.call(arguments, 1);
  642. return function bound() {
  643. var position = 0, length = boundArgs.length;
  644. var args = Array(length);
  645. for (var i = 0; i < length; i++) {
  646. args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
  647. }
  648. while (position < arguments.length) args.push(arguments[position++]);
  649. return executeBound(func, bound, this, this, args);
  650. };
  651. };
  652. // Bind a number of an object's methods to that object. Remaining arguments
  653. // are the method names to be bound. Useful for ensuring that all callbacks
  654. // defined on an object belong to it.
  655. _.bindAll = function(obj) {
  656. var i, length = arguments.length, key;
  657. if (length <= 1) throw new Error('bindAll must be passed function names');
  658. for (i = 1; i < length; i++) {
  659. key = arguments[i];
  660. obj[key] = _.bind(obj[key], obj);
  661. }
  662. return obj;
  663. };
  664. // Memoize an expensive function by storing its results.
  665. _.memoize = function(func, hasher) {
  666. var memoize = function(key) {
  667. var cache = memoize.cache;
  668. var address = '' + (hasher ? hasher.apply(this, arguments) : key);
  669. if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
  670. return cache[address];
  671. };
  672. memoize.cache = {};
  673. return memoize;
  674. };
  675. // Delays a function for the given number of milliseconds, and then calls
  676. // it with the arguments supplied.
  677. _.delay = function(func, wait) {
  678. var args = slice.call(arguments, 2);
  679. return setTimeout(function(){
  680. return func.apply(null, args);
  681. }, wait);
  682. };
  683. // Defers a function, scheduling it to run after the current call stack has
  684. // cleared.
  685. _.defer = _.partial(_.delay, _, 1);
  686. // Returns a function, that, when invoked, will only be triggered at most once
  687. // during a given window of time. Normally, the throttled function will run
  688. // as much as it can, without ever going more than once per `wait` duration;
  689. // but if you'd like to disable the execution on the leading edge, pass
  690. // `{leading: false}`. To disable execution on the trailing edge, ditto.
  691. _.throttle = function(func, wait, options) {
  692. var context, args, result;
  693. var timeout = null;
  694. var previous = 0;
  695. if (!options) options = {};
  696. var later = function() {
  697. previous = options.leading === false ? 0 : _.now();
  698. timeout = null;
  699. result = func.apply(context, args);
  700. if (!timeout) context = args = null;
  701. };
  702. return function() {
  703. var now = _.now();
  704. if (!previous && options.leading === false) previous = now;
  705. var remaining = wait - (now - previous);
  706. context = this;
  707. args = arguments;
  708. if (remaining <= 0 || remaining > wait) {
  709. if (timeout) {
  710. clearTimeout(timeout);
  711. timeout = null;
  712. }
  713. previous = now;
  714. result = func.apply(context, args);
  715. if (!timeout) context = args = null;
  716. } else if (!timeout && options.trailing !== false) {
  717. timeout = setTimeout(later, remaining);
  718. }
  719. return result;
  720. };
  721. };
  722. // Returns a function, that, as long as it continues to be invoked, will not
  723. // be triggered. The function will be called after it stops being called for
  724. // N milliseconds. If `immediate` is passed, trigger the function on the
  725. // leading edge, instead of the trailing.
  726. _.debounce = function(func, wait, immediate) {
  727. var timeout, args, context, timestamp, result;
  728. var later = function() {
  729. var last = _.now() - timestamp;
  730. if (last < wait && last >= 0) {
  731. timeout = setTimeout(later, wait - last);
  732. } else {
  733. timeout = null;
  734. if (!immediate) {
  735. result = func.apply(context, args);
  736. if (!timeout) context = args = null;
  737. }
  738. }
  739. };
  740. return function() {
  741. context = this;
  742. args = arguments;
  743. timestamp = _.now();
  744. var callNow = immediate && !timeout;
  745. if (!timeout) timeout = setTimeout(later, wait);
  746. if (callNow) {
  747. result = func.apply(context, args);
  748. context = args = null;
  749. }
  750. return result;
  751. };
  752. };
  753. // Returns the first function passed as an argument to the second,
  754. // allowing you to adjust arguments, run code before and after, and
  755. // conditionally execute the original function.
  756. _.wrap = function(func, wrapper) {
  757. return _.partial(wrapper, func);
  758. };
  759. // Returns a negated version of the passed-in predicate.
  760. _.negate = function(predicate) {
  761. return function() {
  762. return !predicate.apply(this, arguments);
  763. };
  764. };
  765. // Returns a function that is the composition of a list of functions, each
  766. // consuming the return value of the function that follows.
  767. _.compose = function() {
  768. var args = arguments;
  769. var start = args.length - 1;
  770. return function() {
  771. var i = start;
  772. var result = args[start].apply(this, arguments);
  773. while (i--) result = args[i].call(this, result);
  774. return result;
  775. };
  776. };
  777. // Returns a function that will only be executed on and after the Nth call.
  778. _.after = function(times, func) {
  779. return function() {
  780. if (--times < 1) {
  781. return func.apply(this, arguments);
  782. }
  783. };
  784. };
  785. // Returns a function that will only be executed up to (but not including) the Nth call.
  786. _.before = function(times, func) {
  787. var memo;
  788. return function() {
  789. if (--times > 0) {
  790. memo = func.apply(this, arguments);
  791. }
  792. if (times <= 1) func = null;
  793. return memo;
  794. };
  795. };
  796. // Returns a function that will be executed at most one time, no matter how
  797. // often you call it. Useful for lazy initialization.
  798. _.once = _.partial(_.before, 2);
  799. // Object Functions
  800. // ----------------
  801. // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
  802. var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
  803. var nonEnumerableProps = ['constructor', 'valueOf', 'isPrototypeOf', 'toString',
  804. 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
  805. function collectNonEnumProps(obj, keys) {
  806. var nonEnumIdx = nonEnumerableProps.length;
  807. var proto = typeof obj.constructor === 'function' ? FuncProto : ObjProto;
  808. while (nonEnumIdx--) {
  809. var prop = nonEnumerableProps[nonEnumIdx];
  810. if (prop === 'constructor' ? _.has(obj, prop) : prop in obj &&
  811. obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
  812. keys.push(prop);
  813. }
  814. }
  815. }
  816. // Retrieve the names of an object's own properties.
  817. // Delegates to **ECMAScript 5**'s native `Object.keys`
  818. _.keys = function(obj) {
  819. if (!_.isObject(obj)) return [];
  820. if (nativeKeys) return nativeKeys(obj);
  821. var keys = [];
  822. for (var key in obj) if (_.has(obj, key)) keys.push(key);
  823. // Ahem, IE < 9.
  824. if (hasEnumBug) collectNonEnumProps(obj, keys);
  825. return keys;
  826. };
  827. // Retrieve all the property names of an object.
  828. _.allKeys = function(obj) {
  829. if (!_.isObject(obj)) return [];
  830. var keys = [];
  831. for (var key in obj) keys.push(key);
  832. // Ahem, IE < 9.
  833. if (hasEnumBug) collectNonEnumProps(obj, keys);
  834. return keys;
  835. };
  836. // Retrieve the values of an object's properties.
  837. _.values = function(obj) {
  838. var keys = _.keys(obj);
  839. var length = keys.length;
  840. var values = Array(length);
  841. for (var i = 0; i < length; i++) {
  842. values[i] = obj[keys[i]];
  843. }
  844. return values;
  845. };
  846. // Returns the results of applying the iteratee to each element of the object
  847. // In contrast to _.map it returns an object
  848. _.mapObject = function(obj, iteratee, context) {
  849. iteratee = cb(iteratee, context);
  850. var keys = _.keys(obj),
  851. length = keys.length,
  852. results = {},
  853. currentKey;
  854. for (var index = 0; index < length; index++) {
  855. currentKey = keys[index];
  856. results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
  857. }
  858. return results;
  859. };
  860. // Convert an object into a list of `[key, value]` pairs.
  861. _.pairs = function(obj) {
  862. var keys = _.keys(obj);
  863. var length = keys.length;
  864. var pairs = Array(length);
  865. for (var i = 0; i < length; i++) {
  866. pairs[i] = [keys[i], obj[keys[i]]];
  867. }
  868. return pairs;
  869. };
  870. // Invert the keys and values of an object. The values must be serializable.
  871. _.invert = function(obj) {
  872. var result = {};
  873. var keys = _.keys(obj);
  874. for (var i = 0, length = keys.length; i < length; i++) {
  875. result[obj[keys[i]]] = keys[i];
  876. }
  877. return result;
  878. };
  879. // Return a sorted list of the function names available on the object.
  880. // Aliased as `methods`
  881. _.functions = _.methods = function(obj) {
  882. var names = [];
  883. for (var key in obj) {
  884. if (_.isFunction(obj[key])) names.push(key);
  885. }
  886. return names.sort();
  887. };
  888. // Extend a given object with all the properties in passed-in object(s).
  889. _.extend = createAssigner(_.allKeys);
  890. // Assigns a given object with all the own properties in the passed-in object(s)
  891. // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
  892. _.extendOwn = createAssigner(_.keys);
  893. // Returns the first key on an object that passes a predicate test
  894. _.findKey = function(obj, predicate, context) {
  895. predicate = cb(predicate, context);
  896. var keys = _.keys(obj), key;
  897. for (var i = 0, length = keys.length; i < length; i++) {
  898. key = keys[i];
  899. if (predicate(obj[key], key, obj)) return key;
  900. }
  901. };
  902. // Return a copy of the object only containing the whitelisted properties.
  903. _.pick = function(obj, iteratee, context) {
  904. var result = {}, key;
  905. if (obj == null) return result;
  906. if (_.isFunction(iteratee)) {
  907. iteratee = optimizeCb(iteratee, context);
  908. for (key in obj) {
  909. var value = obj[key];
  910. if (iteratee(value, key, obj)) result[key] = value;
  911. }
  912. } else {
  913. var keys = flatten(arguments, false, false, 1);
  914. obj = new Object(obj);
  915. for (var i = 0, length = keys.length; i < length; i++) {
  916. key = keys[i];
  917. if (key in obj) result[key] = obj[key];
  918. }
  919. }
  920. return result;
  921. };
  922. // Return a copy of the object without the blacklisted properties.
  923. _.omit = function(obj, iteratee, context) {
  924. if (_.isFunction(iteratee)) {
  925. iteratee = _.negate(iteratee);
  926. } else {
  927. var keys = _.map(flatten(arguments, false, false, 1), String);
  928. iteratee = function(value, key) {
  929. return !_.contains(keys, key);
  930. };
  931. }
  932. return _.pick(obj, iteratee, context);
  933. };
  934. // Fill in a given object with default properties.
  935. _.defaults = createAssigner(_.allKeys, true);
  936. // Create a (shallow-cloned) duplicate of an object.
  937. _.clone = function(obj) {
  938. if (!_.isObject(obj)) return obj;
  939. return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  940. };
  941. // Invokes interceptor with the obj, and then returns obj.
  942. // The primary purpose of this method is to "tap into" a method chain, in
  943. // order to perform operations on intermediate results within the chain.
  944. _.tap = function(obj, interceptor) {
  945. interceptor(obj);
  946. return obj;
  947. };
  948. // Returns whether an object has a given set of `key:value` pairs.
  949. _.isMatch = function(object, attrs) {
  950. var keys = _.keys(attrs), length = keys.length;
  951. if (object == null) return !length;
  952. var obj = Object(object);
  953. for (var i = 0; i < length; i++) {
  954. var key = keys[i];
  955. if (attrs[key] !== obj[key] || !(key in obj)) return false;
  956. }
  957. return true;
  958. };
  959. // Internal recursive comparison function for `isEqual`.
  960. var eq = function(a, b, aStack, bStack) {
  961. // Identical objects are equal. `0 === -0`, but they aren't identical.
  962. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
  963. if (a === b) return a !== 0 || 1 / a === 1 / b;
  964. // A strict comparison is necessary because `null == undefined`.
  965. if (a == null || b == null) return a === b;
  966. // Unwrap any wrapped objects.
  967. if (a instanceof _) a = a._wrapped;
  968. if (b instanceof _) b = b._wrapped;
  969. // Compare `[[Class]]` names.
  970. var className = toString.call(a);
  971. if (className !== toString.call(b)) return false;
  972. switch (className) {
  973. // Strings, numbers, regular expressions, dates, and booleans are compared by value.
  974. case '[object RegExp]':
  975. // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
  976. case '[object String]':
  977. // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
  978. // equivalent to `new String("5")`.
  979. return '' + a === '' + b;
  980. case '[object Number]':
  981. // `NaN`s are equivalent, but non-reflexive.
  982. // Object(NaN) is equivalent to NaN
  983. if (+a !== +a) return +b !== +b;
  984. // An `egal` comparison is performed for other numeric values.
  985. return +a === 0 ? 1 / +a === 1 / b : +a === +b;
  986. case '[object Date]':
  987. case '[object Boolean]':
  988. // Coerce dates and booleans to numeric primitive values. Dates are compared by their
  989. // millisecond representations. Note that invalid dates with millisecond representations
  990. // of `NaN` are not equivalent.
  991. return +a === +b;
  992. }
  993. var areArrays = className === '[object Array]';
  994. if (!areArrays) {
  995. if (typeof a != 'object' || typeof b != 'object') return false;
  996. // Objects with different constructors are not equivalent, but `Object`s or `Array`s
  997. // from different frames are.
  998. var aCtor = a.constructor, bCtor = b.constructor;
  999. if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
  1000. _.isFunction(bCtor) && bCtor instanceof bCtor)
  1001. && ('constructor' in a && 'constructor' in b)) {
  1002. return false;
  1003. }
  1004. }
  1005. // Assume equality for cyclic structures. The algorithm for detecting cyclic
  1006. // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
  1007. // Initializing stack of traversed objects.
  1008. // It's done here since we only need them for objects and arrays comparison.
  1009. aStack = aStack || [];
  1010. bStack = bStack || [];
  1011. var length = aStack.length;
  1012. while (length--) {
  1013. // Linear search. Performance is inversely proportional to the number of
  1014. // unique nested structures.
  1015. if (aStack[length] === a) return bStack[length] === b;
  1016. }
  1017. // Add the first object to the stack of traversed objects.
  1018. aStack.push(a);
  1019. bStack.push(b);
  1020. // Recursively compare objects and arrays.
  1021. if (areArrays) {
  1022. // Compare array lengths to determine if a deep comparison is necessary.
  1023. length = a.length;
  1024. if (length !== b.length) return false;
  1025. // Deep compare the contents, ignoring non-numeric properties.
  1026. while (length--) {
  1027. if (!eq(a[length], b[length], aStack, bStack)) return false;
  1028. }
  1029. } else {
  1030. // Deep compare objects.
  1031. var keys = _.keys(a), key;
  1032. length = keys.length;
  1033. // Ensure that both objects contain the same number of properties before comparing deep equality.
  1034. if (_.keys(b).length !== length) return false;
  1035. while (length--) {
  1036. // Deep compare each member
  1037. key = keys[length];
  1038. if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
  1039. }
  1040. }
  1041. // Remove the first object from the stack of traversed objects.
  1042. aStack.pop();
  1043. bStack.pop();
  1044. return true;
  1045. };
  1046. // Perform a deep comparison to check if two objects are equal.
  1047. _.isEqual = function(a, b) {
  1048. return eq(a, b);
  1049. };
  1050. // Is a given array, string, or object empty?
  1051. // An "empty" object has no enumerable own-properties.
  1052. _.isEmpty = function(obj) {
  1053. if (obj == null) return true;
  1054. if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
  1055. return _.keys(obj).length === 0;
  1056. };
  1057. // Is a given value a DOM element?
  1058. _.isElement = function(obj) {
  1059. return !!(obj && obj.nodeType === 1);
  1060. };
  1061. // Is a given value an array?
  1062. // Delegates to ECMA5's native Array.isArray
  1063. _.isArray = nativeIsArray || function(obj) {
  1064. return toString.call(obj) === '[object Array]';
  1065. };
  1066. // Is a given variable an object?
  1067. _.isObject = function(obj) {
  1068. var type = typeof obj;
  1069. return type === 'function' || type === 'object' && !!obj;
  1070. };
  1071. // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
  1072. _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
  1073. _['is' + name] = function(obj) {
  1074. return toString.call(obj) === '[object ' + name + ']';
  1075. };
  1076. });
  1077. // Define a fallback version of the method in browsers (ahem, IE < 9), where
  1078. // there isn't any inspectable "Arguments" type.
  1079. if (!_.isArguments(arguments)) {
  1080. _.isArguments = function(obj) {
  1081. return _.has(obj, 'callee');
  1082. };
  1083. }
  1084. // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
  1085. // IE 11 (#1621), and in Safari 8 (#1929).
  1086. if (typeof /./ != 'function' && typeof Int8Array != 'object') {
  1087. _.isFunction = function(obj) {
  1088. return typeof obj == 'function' || false;
  1089. };
  1090. }
  1091. // Is a given object a finite number?
  1092. _.isFinite = function(obj) {
  1093. return isFinite(obj) && !isNaN(parseFloat(obj));
  1094. };
  1095. // Is the given value `NaN`? (NaN is the only number which does not equal itself).
  1096. _.isNaN = function(obj) {
  1097. return _.isNumber(obj) && obj !== +obj;
  1098. };
  1099. // Is a given value a boolean?
  1100. _.isBoolean = function(obj) {
  1101. return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
  1102. };
  1103. // Is a given value equal to null?
  1104. _.isNull = function(obj) {
  1105. return obj === null;
  1106. };
  1107. // Is a given variable undefined?
  1108. _.isUndefined = function(obj) {
  1109. return obj === void 0;
  1110. };
  1111. // Shortcut function for checking if an object has a given property directly
  1112. // on itself (in other words, not on a prototype).
  1113. _.has = function(obj, key) {
  1114. return obj != null && hasOwnProperty.call(obj, key);
  1115. };
  1116. // Utility Functions
  1117. // -----------------
  1118. // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  1119. // previous owner. Returns a reference to the Underscore object.
  1120. _.noConflict = function() {
  1121. root._ = previousUnderscore;
  1122. return this;
  1123. };
  1124. // Keep the identity function around for default iteratees.
  1125. _.identity = function(value) {
  1126. return value;
  1127. };
  1128. // Predicate-generating functions. Often useful outside of Underscore.
  1129. _.constant = function(value) {
  1130. return function() {
  1131. return value;
  1132. };
  1133. };
  1134. _.noop = function(){};
  1135. _.property = function(key) {
  1136. return function(obj) {
  1137. return obj == null ? void 0 : obj[key];
  1138. };
  1139. };
  1140. // Generates a function for a given object that returns a given property.
  1141. _.propertyOf = function(obj) {
  1142. return obj == null ? function(){} : function(key) {
  1143. return obj[key];
  1144. };
  1145. };
  1146. // Returns a predicate for checking whether an object has a given set of
  1147. // `key:value` pairs.
  1148. _.matcher = _.matches = function(attrs) {
  1149. attrs = _.extendOwn({}, attrs);
  1150. return function(obj) {
  1151. return _.isMatch(obj, attrs);
  1152. };
  1153. };
  1154. // Run a function **n** times.
  1155. _.times = function(n, iteratee, context) {
  1156. var accum = Array(Math.max(0, n));
  1157. iteratee = optimizeCb(iteratee, context, 1);
  1158. for (var i = 0; i < n; i++) accum[i] = iteratee(i);
  1159. return accum;
  1160. };
  1161. // Return a random integer between min and max (inclusive).
  1162. _.random = function(min, max) {
  1163. if (max == null) {
  1164. max = min;
  1165. min = 0;
  1166. }
  1167. return min + Math.floor(Math.random() * (max - min + 1));
  1168. };
  1169. // A (possibly faster) way to get the current timestamp as an integer.
  1170. _.now = Date.now || function() {
  1171. return new Date().getTime();
  1172. };
  1173. // List of HTML entities for escaping.
  1174. var escapeMap = {
  1175. '&': '&amp;',
  1176. '<': '&lt;',
  1177. '>': '&gt;',
  1178. '"': '&quot;',
  1179. "'": '&#x27;',
  1180. '`': '&#x60;'
  1181. };
  1182. var unescapeMap = _.invert(escapeMap);
  1183. // Functions for escaping and unescaping strings to/from HTML interpolation.
  1184. var createEscaper = function(map) {
  1185. var escaper = function(match) {
  1186. return map[match];
  1187. };
  1188. // Regexes for identifying a key that needs to be escaped
  1189. var source = '(?:' + _.keys(map).join('|') + ')';
  1190. var testRegexp = RegExp(source);
  1191. var replaceRegexp = RegExp(source, 'g');
  1192. return function(string) {
  1193. string = string == null ? '' : '' + string;
  1194. return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
  1195. };
  1196. };
  1197. _.escape = createEscaper(escapeMap);
  1198. _.unescape = createEscaper(unescapeMap);
  1199. // If the value of the named `property` is a function then invoke it with the
  1200. // `object` as context; otherwise, return it.
  1201. _.result = function(object, property, fallback) {
  1202. var value = object == null ? void 0 : object[property];
  1203. if (value === void 0) {
  1204. value = fallback;
  1205. }
  1206. return _.isFunction(value) ? value.call(object) : value;
  1207. };
  1208. // Generate a unique integer id (unique within the entire client session).
  1209. // Useful for temporary DOM ids.
  1210. var idCounter = 0;
  1211. _.uniqueId = function(prefix) {
  1212. var id = ++idCounter + '';
  1213. return prefix ? prefix + id : id;
  1214. };
  1215. // By default, Underscore uses ERB-style template delimiters, change the
  1216. // following template settings to use alternative delimiters.
  1217. _.templateSettings = {
  1218. evaluate : /<%([\s\S]+?)%>/g,
  1219. interpolate : /<%=([\s\S]+?)%>/g,
  1220. escape : /<%-([\s\S]+?)%>/g
  1221. };
  1222. // When customizing `templateSettings`, if you don't want to define an
  1223. // interpolation, evaluation or escaping regex, we need one that is
  1224. // guaranteed not to match.
  1225. var noMatch = /(.)^/;
  1226. // Certain characters need to be escaped so that they can be put into a
  1227. // string literal.
  1228. var escapes = {
  1229. "'": "'",
  1230. '\\': '\\',
  1231. '\r': 'r',
  1232. '\n': 'n',
  1233. '\u2028': 'u2028',
  1234. '\u2029': 'u2029'
  1235. };
  1236. var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
  1237. var escapeChar = function(match) {
  1238. return '\\' + escapes[match];
  1239. };
  1240. // JavaScript micro-templating, similar to John Resig's implementation.
  1241. // Underscore templating handles arbitrary delimiters, preserves whitespace,
  1242. // and correctly escapes quotes within interpolated code.
  1243. // NB: `oldSettings` only exists for backwards compatibility.
  1244. _.template = function(text, settings, oldSettings) {
  1245. if (!settings && oldSettings) settings = oldSettings;
  1246. settings = _.defaults({}, settings, _.templateSettings);
  1247. // Combine delimiters into one regular expression via alternation.
  1248. var matcher = RegExp([
  1249. (settings.escape || noMatch).source,
  1250. (settings.interpolate || noMatch).source,
  1251. (settings.evaluate || noMatch).source
  1252. ].join('|') + '|$', 'g');
  1253. // Compile the template source, escaping string literals appropriately.
  1254. var index = 0;
  1255. var source = "__p+='";
  1256. text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
  1257. source += text.slice(index, offset).replace(escaper, escapeChar);
  1258. index = offset + match.length;
  1259. if (escape) {
  1260. source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
  1261. } else if (interpolate) {
  1262. source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
  1263. } else if (evaluate) {
  1264. source += "';\n" + evaluate + "\n__p+='";
  1265. }
  1266. // Adobe VMs need the match returned to produce the correct offest.
  1267. return match;
  1268. });
  1269. source += "';\n";
  1270. // If a variable is not specified, place data values in local scope.
  1271. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
  1272. source = "var __t,__p='',__j=Array.prototype.join," +
  1273. "print=function(){__p+=__j.call(arguments,'');};\n" +
  1274. source + 'return __p;\n';
  1275. try {
  1276. var render = new Function(settings.variable || 'obj', '_', source);
  1277. } catch (e) {
  1278. e.source = source;
  1279. throw e;
  1280. }
  1281. var template = function(data) {
  1282. return render.call(this, data, _);
  1283. };
  1284. // Provide the compiled source as a convenience for precompilation.
  1285. var argument = settings.variable || 'obj';
  1286. template.source = 'function(' + argument + '){\n' + source + '}';
  1287. return template;
  1288. };
  1289. // Add a "chain" function. Start chaining a wrapped Underscore object.
  1290. _.chain = function(obj) {
  1291. var instance = _(obj);
  1292. instance._chain = true;
  1293. return instance;
  1294. };
  1295. // OOP
  1296. // ---------------
  1297. // If Underscore is called as a function, it returns a wrapped object that
  1298. // can be used OO-style. This wrapper holds altered versions of all the
  1299. // underscore functions. Wrapped objects may be chained.
  1300. // Helper function to continue chaining intermediate results.
  1301. var result = function(instance, obj) {
  1302. return instance._chain ? _(obj).chain() : obj;
  1303. };
  1304. // Add your own custom funct