underscore.js 44 KB

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