underscore.js 47 KB

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