underscore.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. // Underscore.js 1.4.4
  2. // ===================
  3. // > http://underscorejs.org
  4. // > (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
  5. // > Underscore may be freely distributed under the MIT license.
  6. // Baseline setup
  7. // --------------
  8. (function() {
  9. // Establish the root object, `window` in the browser, or `global` on the server.
  10. var root = this;
  11. // Save the previous value of the `_` variable.
  12. var previousUnderscore = root._;
  13. // Establish the object that gets returned to break out of a loop iteration.
  14. var breaker = {};
  15. // Save bytes in the minified (but not gzipped) version:
  16. var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
  17. // Create quick reference variables for speed access to core prototypes.
  18. var 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.4.4';
  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;
  65. if (nativeForEach && obj.forEach === nativeForEach) {
  66. obj.forEach(iterator, context);
  67. } else if (obj.length === +obj.length) {
  68. for (var i = 0, l = obj.length; i < l; i++) {
  69. if (iterator.call(context, obj[i], i, obj) === breaker) return;
  70. }
  71. } else {
  72. for (var key in obj) {
  73. if (_.has(obj, key)) {
  74. if (iterator.call(context, obj[key], key, obj) === breaker) return;
  75. }
  76. }
  77. }
  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[results.length] = 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, iterator, context) {
  139. var result;
  140. any(obj, function(value, index, list) {
  141. if (iterator.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, iterator, context) {
  152. var results = [];
  153. if (obj == null) return results;
  154. if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
  155. each(obj, function(value, index, list) {
  156. if (iterator.call(context, value, index, list)) results[results.length] = value;
  157. });
  158. return results;
  159. };
  160. // Return all the elements for which a truth test fails.
  161. _.reject = function(obj, iterator, context) {
  162. return _.filter(obj, function(value, index, list) {
  163. return !iterator.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, iterator, context) {
  170. iterator || (iterator = _.identity);
  171. var result = true;
  172. if (obj == null) return result;
  173. if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
  174. each(obj, function(value, index, list) {
  175. if (!(result = result && iterator.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, iterator, context) {
  183. iterator || (iterator = _.identity);
  184. var result = false;
  185. if (obj == null) return result;
  186. if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
  187. each(obj, function(value, index, list) {
  188. if (result || (result = iterator.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, function(value){ return value[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, first) {
  216. if (_.isEmpty(attrs)) return first ? null : [];
  217. return _[first ? 'find' : 'filter'](obj, function(value) {
  218. for (var key in attrs) {
  219. if (attrs[key] !== value[key]) return false;
  220. }
  221. return true;
  222. });
  223. };
  224. // Convenience version of a common use case of `find`: getting the first object
  225. // containing specific `key:value` pairs.
  226. _.findWhere = function(obj, attrs) {
  227. return _.where(obj, attrs, true);
  228. };
  229. // Return the maximum element or (element-based computation).
  230. // Can't optimize arrays of integers longer than 65,535 elements.
  231. // See: https://bugs.webkit.org/show_bug.cgi?id=80797
  232. _.max = function(obj, iterator, context) {
  233. if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
  234. return Math.max.apply(Math, obj);
  235. }
  236. if (!iterator && _.isEmpty(obj)) return -Infinity;
  237. var result = {computed : -Infinity, value: -Infinity};
  238. each(obj, function(value, index, list) {
  239. var computed = iterator ? iterator.call(context, value, index, list) : value;
  240. computed >= result.computed && (result = {value : value, computed : computed});
  241. });
  242. return result.value;
  243. };
  244. // Return the minimum element (or element-based computation).
  245. _.min = function(obj, iterator, context) {
  246. if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
  247. return Math.min.apply(Math, obj);
  248. }
  249. if (!iterator && _.isEmpty(obj)) return Infinity;
  250. var result = {computed : Infinity, value: Infinity};
  251. each(obj, function(value, index, list) {
  252. var computed = iterator ? iterator.call(context, value, index, list) : value;
  253. computed < result.computed && (result = {value : value, computed : computed});
  254. });
  255. return result.value;
  256. };
  257. // Shuffle an array.
  258. _.shuffle = function(obj) {
  259. var rand;
  260. var index = 0;
  261. var shuffled = [];
  262. each(obj, function(value) {
  263. rand = _.random(index++);
  264. shuffled[index - 1] = shuffled[rand];
  265. shuffled[rand] = value;
  266. });
  267. return shuffled;
  268. };
  269. // An internal function to generate lookup iterators.
  270. var lookupIterator = function(value) {
  271. return _.isFunction(value) ? value : function(obj){ return obj[value]; };
  272. };
  273. // Sort the object's values by a criterion produced by an iterator.
  274. _.sortBy = function(obj, value, context) {
  275. var iterator = lookupIterator(value);
  276. return _.pluck(_.map(obj, function(value, index, list) {
  277. return {
  278. value : value,
  279. index : index,
  280. criteria : iterator.call(context, value, index, list)
  281. };
  282. }).sort(function(left, right) {
  283. var a = left.criteria;
  284. var b = right.criteria;
  285. if (a !== b) {
  286. if (a > b || a === void 0) return 1;
  287. if (a < b || b === void 0) return -1;
  288. }
  289. return left.index < right.index ? -1 : 1;
  290. }), 'value');
  291. };
  292. // An internal function used for aggregate "group by" operations.
  293. var group = function(obj, value, context, behavior) {
  294. var result = {};
  295. var iterator = lookupIterator(value || _.identity);
  296. each(obj, function(value, index) {
  297. var key = iterator.call(context, value, index, obj);
  298. behavior(result, key, value);
  299. });
  300. return result;
  301. };
  302. // Groups the object's values by a criterion. Pass either a string attribute
  303. // to group by, or a function that returns the criterion.
  304. _.groupBy = function(obj, value, context) {
  305. return group(obj, value, context, function(result, key, value) {
  306. (_.has(result, key) ? result[key] : (result[key] = [])).push(value);
  307. });
  308. };
  309. // Counts instances of an object that group by a certain criterion. Pass
  310. // either a string attribute to count by, or a function that returns the
  311. // criterion.
  312. _.countBy = function(obj, value, context) {
  313. return group(obj, value, context, function(result, key) {
  314. if (!_.has(result, key)) result[key] = 0;
  315. result[key]++;
  316. });
  317. };
  318. // Use a comparator function to figure out the smallest index at which
  319. // an object should be inserted so as to maintain order. Uses binary search.
  320. _.sortedIndex = function(array, obj, iterator, context) {
  321. iterator = iterator == null ? _.identity : lookupIterator(iterator);
  322. var value = iterator.call(context, obj);
  323. var low = 0, high = array.length;
  324. while (low < high) {
  325. var mid = (low + high) >>> 1;
  326. iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
  327. }
  328. return low;
  329. };
  330. // Safely convert anything iterable into a real, live array.
  331. _.toArray = function(obj) {
  332. if (!obj) return [];
  333. if (_.isArray(obj)) return slice.call(obj);
  334. if (obj.length === +obj.length) return _.map(obj, _.identity);
  335. return _.values(obj);
  336. };
  337. // Return the number of elements in an object.
  338. _.size = function(obj) {
  339. if (obj == null) return 0;
  340. return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
  341. };
  342. // Array Functions
  343. // ---------------
  344. // Get the first element of an array. Passing **n** will return the first N
  345. // values in the array. Aliased as `head` and `take`. The **guard** check
  346. // allows it to work with `_.map`.
  347. _.first = _.head = _.take = function(array, n, guard) {
  348. if (array == null) return void 0;
  349. return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  350. };
  351. // Returns everything but the last entry of the array. Especially useful on
  352. // the arguments object. Passing **n** will return all the values in
  353. // the array, excluding the last N. The **guard** check allows it to work with
  354. // `_.map`.
  355. _.initial = function(array, n, guard) {
  356. return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
  357. };
  358. // Get the last element of an array. Passing **n** will return the last N
  359. // values in the array. The **guard** check allows it to work with `_.map`.
  360. _.last = function(array, n, guard) {
  361. if (array == null) return void 0;
  362. if ((n != null) && !guard) {
  363. return slice.call(array, Math.max(array.length - n, 0));
  364. } else {
  365. return array[array.length - 1];
  366. }
  367. };
  368. // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
  369. // Especially useful on the arguments object. Passing an **n** will return
  370. // the rest N values in the array. The **guard**
  371. // check allows it to work with `_.map`.
  372. _.rest = _.tail = _.drop = function(array, n, guard) {
  373. return slice.call(array, (n == null) || guard ? 1 : n);
  374. };
  375. // Trim out all falsy values from an array.
  376. _.compact = function(array) {
  377. return _.filter(array, _.identity);
  378. };
  379. // Internal implementation of a recursive `flatten` function.
  380. var flatten = function(input, shallow, output) {
  381. each(input, function(value) {
  382. if (_.isArray(value)) {
  383. shallow ? push.apply(output, value) : flatten(value, shallow, output);
  384. } else {
  385. output.push(value);
  386. }
  387. });
  388. return output;
  389. };
  390. // Return a completely flattened version of an array.
  391. _.flatten = function(array, shallow) {
  392. return flatten(array, shallow, []);
  393. };
  394. // Return a version of the array that does not contain the specified value(s).
  395. _.without = function(array) {
  396. return _.difference(array, slice.call(arguments, 1));
  397. };
  398. // Produce a duplicate-free version of the array. If the array has already
  399. // been sorted, you have the option of using a faster algorithm.
  400. // Aliased as `unique`.
  401. _.uniq = _.unique = function(array, isSorted, iterator, context) {
  402. if (_.isFunction(isSorted)) {
  403. context = iterator;
  404. iterator = isSorted;
  405. isSorted = false;
  406. }
  407. var initial = iterator ? _.map(array, iterator, context) : array;
  408. var results = [];
  409. var seen = [];
  410. each(initial, function(value, index) {
  411. if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
  412. seen.push(value);
  413. results.push(array[index]);
  414. }
  415. });
  416. return results;
  417. };
  418. // Produce an array that contains the union: each distinct element from all of
  419. // the passed-in arrays.
  420. _.union = function() {
  421. return _.uniq(concat.apply(ArrayProto, arguments));
  422. };
  423. // Produce an array that contains every item shared between all the
  424. // passed-in arrays.
  425. _.intersection = function(array) {
  426. var rest = slice.call(arguments, 1);
  427. return _.filter(_.uniq(array), function(item) {
  428. return _.every(rest, function(other) {
  429. return _.indexOf(other, item) >= 0;
  430. });
  431. });
  432. };
  433. // Take the difference between one array and a number of other arrays.
  434. // Only the elements present in just the first array will remain.
  435. _.difference = function(array) {
  436. var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
  437. return _.filter(array, function(value){ return !_.contains(rest, value); });
  438. };
  439. // Zip together multiple lists into a single array -- elements that share
  440. // an index go together.
  441. _.zip = function() {
  442. var args = slice.call(arguments);
  443. var length = _.max(_.pluck(args, 'length'));
  444. var results = new Array(length);
  445. for (var i = 0; i < length; i++) {
  446. results[i] = _.pluck(args, "" + i);
  447. }
  448. return results;
  449. };
  450. // Converts lists into objects. Pass either a single array of `[key, value]`
  451. // pairs, or two parallel arrays of the same length -- one of keys, and one of
  452. // the corresponding values.
  453. _.object = function(list, values) {
  454. if (list == null) return {};
  455. var result = {};
  456. for (var i = 0, l = list.length; i < l; i++) {
  457. if (values) {
  458. result[list[i]] = values[i];
  459. } else {
  460. result[list[i][0]] = list[i][1];
  461. }
  462. }
  463. return result;
  464. };
  465. // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
  466. // we need this function. Return the position of the first occurrence of an
  467. // item in an array, or -1 if the item is not included in the array.
  468. // Delegates to **ECMAScript 5**'s native `indexOf` if available.
  469. // If the array is large and already in sort order, pass `true`
  470. // for **isSorted** to use binary search.
  471. _.indexOf = function(array, item, isSorted) {
  472. if (array == null) return -1;
  473. var i = 0, l = array.length;
  474. if (isSorted) {
  475. if (typeof isSorted == 'number') {
  476. i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
  477. } else {
  478. i = _.sortedIndex(array, item);
  479. return array[i] === item ? i : -1;
  480. }
  481. }
  482. if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
  483. for (; i < l; i++) if (array[i] === item) return i;
  484. return -1;
  485. };
  486. // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
  487. _.lastIndexOf = function(array, item, from) {
  488. if (array == null) return -1;
  489. var hasIndex = from != null;
  490. if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
  491. return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
  492. }
  493. var i = (hasIndex ? from : array.length);
  494. while (i--) if (array[i] === item) return i;
  495. return -1;
  496. };
  497. // Generate an integer Array containing an arithmetic progression. A port of
  498. // the native Python `range()` function. See
  499. // [the Python documentation](http://docs.python.org/library/functions.html#range).
  500. _.range = function(start, stop, step) {
  501. if (arguments.length <= 1) {
  502. stop = start || 0;
  503. start = 0;
  504. }
  505. step = arguments[2] || 1;
  506. var len = Math.max(Math.ceil((stop - start) / step), 0);
  507. var idx = 0;
  508. var range = new Array(len);
  509. while(idx < len) {
  510. range[idx++] = start;
  511. start += step;
  512. }
  513. return range;
  514. };
  515. // Function (ahem) Functions
  516. // ------------------
  517. // Create a function bound to a given object (assigning `this`, and arguments,
  518. // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
  519. // available.
  520. _.bind = function(func, context) {
  521. if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
  522. var args = slice.call(arguments, 2);
  523. return function() {
  524. return func.apply(context, args.concat(slice.call(arguments)));
  525. };
  526. };
  527. // Partially apply a function by creating a version that has had some of its
  528. // arguments pre-filled, without changing its dynamic `this` context.
  529. _.partial = function(func) {
  530. var args = slice.call(arguments, 1);
  531. return function() {
  532. return func.apply(this, args.concat(slice.call(arguments)));
  533. };
  534. };
  535. // Bind all of an object's methods to that object. Useful for ensuring that
  536. // all callbacks defined on an object belong to it.
  537. _.bindAll = function(obj) {
  538. var funcs = slice.call(arguments, 1);
  539. if (funcs.length === 0) funcs = _.functions(obj);
  540. each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
  541. return obj;
  542. };
  543. // Memoize an expensive function by storing its results.
  544. _.memoize = function(func, hasher) {
  545. var memo = {};
  546. hasher || (hasher = _.identity);
  547. return function() {
  548. var key = hasher.apply(this, arguments);
  549. return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
  550. };
  551. };
  552. // Delays a function for the given number of milliseconds, and then calls
  553. // it with the arguments supplied.
  554. _.delay = function(func, wait) {
  555. var args = slice.call(arguments, 2);
  556. return setTimeout(function(){ return func.apply(null, args); }, wait);
  557. };
  558. // Defers a function, scheduling it to run after the current call stack has
  559. // cleared.
  560. _.defer = function(func) {
  561. return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
  562. };
  563. // Returns a function, that, when invoked, will only be triggered at most once
  564. // during a given window of time.
  565. _.throttle = function(func, wait) {
  566. var context, args, timeout, result;
  567. var previous = 0;
  568. var later = function() {
  569. previous = new Date;
  570. timeout = null;
  571. result = func.apply(context, args);
  572. };
  573. return function() {
  574. var now = new Date;
  575. var remaining = wait - (now - previous);
  576. context = this;
  577. args = arguments;
  578. if (remaining <= 0) {
  579. clearTimeout(timeout);
  580. timeout = null;
  581. previous = now;
  582. result = func.apply(context, args);
  583. } else if (!timeout) {
  584. timeout = setTimeout(later, remaining);
  585. }
  586. return result;
  587. };
  588. };
  589. // Returns a function, that, as long as it continues to be invoked, will not
  590. // be triggered. The function will be called after it stops being called for
  591. // N milliseconds. If `immediate` is passed, trigger the function on the
  592. // leading edge, instead of the trailing.
  593. _.debounce = function(func, wait, immediate) {
  594. var timeout, result;
  595. return function() {
  596. var context = this, args = arguments;
  597. var later = function() {
  598. timeout = null;
  599. if (!immediate) result = func.apply(context, args);
  600. };
  601. var callNow = immediate && !timeout;
  602. clearTimeout(timeout);
  603. timeout = setTimeout(later, wait);
  604. if (callNow) result = func.apply(context, args);
  605. return result;
  606. };
  607. };
  608. // Returns a function that will be executed at most one time, no matter how
  609. // often you call it. Useful for lazy initialization.
  610. _.once = function(func) {
  611. var ran = false, memo;
  612. return function() {
  613. if (ran) return memo;
  614. ran = true;
  615. memo = func.apply(this, arguments);
  616. func = null;
  617. return memo;
  618. };
  619. };
  620. // Returns the first function passed as an argument to the second,
  621. // allowing you to adjust arguments, run code before and after, and
  622. // conditionally execute the original function.
  623. _.wrap = function(func, wrapper) {
  624. return function() {
  625. var args = [func];
  626. push.apply(args, arguments);
  627. return wrapper.apply(this, args);
  628. };
  629. };
  630. // Returns a function that is the composition of a list of functions, each
  631. // consuming the return value of the function that follows.
  632. _.compose = function() {
  633. var funcs = arguments;
  634. return function() {
  635. var args = arguments;
  636. for (var i = funcs.length - 1; i >= 0; i--) {
  637. args = [funcs[i].apply(this, args)];
  638. }
  639. return args[0];
  640. };
  641. };
  642. // Returns a function that will only be executed after being called N times.
  643. _.after = function(times, func) {
  644. if (times <= 0) return func();
  645. return function() {
  646. if (--times < 1) {
  647. return func.apply(this, arguments);
  648. }
  649. };
  650. };
  651. // Object Functions
  652. // ----------------
  653. // Retrieve the names of an object's properties.
  654. // Delegates to **ECMAScript 5**'s native `Object.keys`
  655. _.keys = nativeKeys || function(obj) {
  656. if (obj !== Object(obj)) throw new TypeError('Invalid object');
  657. var keys = [];
  658. for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
  659. return keys;
  660. };
  661. // Retrieve the values of an object's properties.
  662. _.values = function(obj) {
  663. var values = [];
  664. for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
  665. return values;
  666. };
  667. // Convert an object into a list of `[key, value]` pairs.
  668. _.pairs = function(obj) {
  669. var pairs = [];
  670. for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
  671. return pairs;
  672. };
  673. // Invert the keys and values of an object. The values must be serializable.
  674. _.invert = function(obj) {
  675. var result = {};
  676. for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
  677. return result;
  678. };
  679. // Return a sorted list of the function names available on the object.
  680. // Aliased as `methods`
  681. _.functions = _.methods = function(obj) {
  682. var names = [];
  683. for (var key in obj) {
  684. if (_.isFunction(obj[key])) names.push(key);
  685. }
  686. return names.sort();
  687. };
  688. // Extend a given object with all the properties in passed-in object(s).
  689. _.extend = function(obj) {
  690. each(slice.call(arguments, 1), function(source) {
  691. if (source) {
  692. for (var prop in source) {
  693. obj[prop] = source[prop];
  694. }
  695. }
  696. });
  697. return obj;
  698. };
  699. // Return a copy of the object only containing the whitelisted properties.
  700. _.pick = function(obj) {
  701. var copy = {};
  702. var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
  703. each(keys, function(key) {
  704. if (key in obj) copy[key] = obj[key];
  705. });
  706. return copy;
  707. };
  708. // Return a copy of the object without the blacklisted properties.
  709. _.omit = function(obj) {
  710. var copy = {};
  711. var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
  712. for (var key in obj) {
  713. if (!_.contains(keys, key)) copy[key] = obj[key];
  714. }
  715. return copy;
  716. };
  717. // Fill in a given object with default properties.
  718. _.defaults = function(obj) {
  719. each(slice.call(arguments, 1), function(source) {
  720. if (source) {
  721. for (var prop in source) {
  722. if (obj[prop] == null) obj[prop] = source[prop];
  723. }
  724. }
  725. });
  726. return obj;
  727. };
  728. // Create a (shallow-cloned) duplicate of an object.
  729. _.clone = function(obj) {
  730. if (!_.isObject(obj)) return obj;
  731. return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  732. };
  733. // Invokes interceptor with the obj, and then returns obj.
  734. // The primary purpose of this method is to "tap into" a method chain, in
  735. // order to perform operations on intermediate results within the chain.
  736. _.tap = function(obj, interceptor) {
  737. interceptor(obj);
  738. return obj;
  739. };
  740. // Internal recursive comparison function for `isEqual`.
  741. var eq = function(a, b, aStack, bStack) {
  742. // Identical objects are equal. `0 === -0`, but they aren't identical.
  743. // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
  744. if (a === b) return a !== 0 || 1 / a == 1 / b;
  745. // A strict comparison is necessary because `null == undefined`.
  746. if (a == null || b == null) return a === b;
  747. // Unwrap any wrapped objects.
  748. if (a instanceof _) a = a._wrapped;
  749. if (b instanceof _) b = b._wrapped;
  750. // Compare `[[Class]]` names.
  751. var className = toString.call(a);
  752. if (className != toString.call(b)) return false;
  753. switch (className) {
  754. // Strings, numbers, dates, and booleans are compared by value.
  755. case '[object String]':
  756. // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
  757. // equivalent to `new String("5")`.
  758. return a == String(b);
  759. case '[object Number]':
  760. // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
  761. // other numeric values.
  762. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
  763. case '[object Date]':
  764. case '[object Boolean]':
  765. // Coerce dates and booleans to numeric primitive values. Dates are compared by their
  766. // millisecond representations. Note that invalid dates with millisecond representations
  767. // of `NaN` are not equivalent.
  768. return +a == +b;
  769. // RegExps are compared by their source patterns and flags.
  770. case '[object RegExp]':
  771. return a.source == b.source &&
  772. a.global == b.global &&
  773. a.multiline == b.multiline &&
  774. a.ignoreCase == b.ignoreCase;
  775. }
  776. if (typeof a != 'object' || typeof b != 'object') return false;
  777. // Assume equality for cyclic structures. The algorithm for detecting cyclic
  778. // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
  779. var length = aStack.length;
  780. while (length--) {
  781. // Linear search. Performance is inversely proportional to the number of
  782. // unique nested structures.
  783. if (aStack[length] == a) return bStack[length] == b;
  784. }
  785. // Add the first object to the stack of traversed objects.
  786. aStack.push(a);
  787. bStack.push(b);
  788. var size = 0, result = true;
  789. // Recursively compare objects and arrays.
  790. if (className == '[object Array]') {
  791. // Compare array lengths to determine if a deep comparison is necessary.
  792. size = a.length;
  793. result = size == b.length;
  794. if (result) {
  795. // Deep compare the contents, ignoring non-numeric properties.
  796. while (size--) {
  797. if (!(result = eq(a[size], b[size], aStack, bStack))) break;
  798. }
  799. }
  800. } else {
  801. // Objects with different constructors are not equivalent, but `Object`s
  802. // from different frames are.
  803. var aCtor = a.constructor, bCtor = b.constructor;
  804. if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
  805. _.isFunction(bCtor) && (bCtor instanceof bCtor))) {
  806. return false;
  807. }
  808. // Deep compare objects.
  809. for (var key in a) {
  810. if (_.has(a, key)) {
  811. // Count the expected number of properties.
  812. size++;
  813. // Deep compare each member.
  814. if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
  815. }
  816. }
  817. // Ensure that both objects contain the same number of properties.
  818. if (result) {
  819. for (key in b) {
  820. if (_.has(b, key) && !(size--)) break;
  821. }
  822. result = !size;
  823. }
  824. }
  825. // Remove the first object from the stack of traversed objects.
  826. aStack.pop();
  827. bStack.pop();
  828. return result;
  829. };
  830. // Perform a deep comparison to check if two objects are equal.
  831. _.isEqual = function(a, b) {
  832. return eq(a, b, [], []);
  833. };
  834. // Is a given array, string, or object empty?
  835. // An "empty" object has no enumerable own-properties.
  836. _.isEmpty = function(obj) {
  837. if (obj == null) return true;
  838. if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
  839. for (var key in obj) if (_.has(obj, key)) return false;
  840. return true;
  841. };
  842. // Is a given value a DOM element?
  843. _.isElement = function(obj) {
  844. return !!(obj && obj.nodeType === 1);
  845. };
  846. // Is a given value an array?
  847. // Delegates to ECMA5's native Array.isArray
  848. _.isArray = nativeIsArray || function(obj) {
  849. return toString.call(obj) == '[object Array]';
  850. };
  851. // Is a given variable an object?
  852. _.isObject = function(obj) {
  853. return obj === Object(obj);
  854. };
  855. // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
  856. each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
  857. _['is' + name] = function(obj) {
  858. return toString.call(obj) == '[object ' + name + ']';
  859. };
  860. });
  861. // Define a fallback version of the method in browsers (ahem, IE), where
  862. // there isn't any inspectable "Arguments" type.
  863. if (!_.isArguments(arguments)) {
  864. _.isArguments = function(obj) {
  865. return !!(obj && _.has(obj, 'callee'));
  866. };
  867. }
  868. // Optimize `isFunction` if appropriate.
  869. if (typeof (/./) !== 'function') {
  870. _.isFunction = function(obj) {
  871. return typeof obj === 'function';
  872. };
  873. }
  874. // Is a given object a finite number?
  875. _.isFinite = function(obj) {
  876. return isFinite(obj) && !isNaN(parseFloat(obj));
  877. };
  878. // Is the given value `NaN`? (NaN is the only number which does not equal itself).
  879. _.isNaN = function(obj) {
  880. return _.isNumber(obj) && obj != +obj;
  881. };
  882. // Is a given value a boolean?
  883. _.isBoolean = function(obj) {
  884. return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
  885. };
  886. // Is a given value equal to null?
  887. _.isNull = function(obj) {
  888. return obj === null;
  889. };
  890. // Is a given variable undefined?
  891. _.isUndefined = function(obj) {
  892. return obj === void 0;
  893. };
  894. // Shortcut function for checking if an object has a given property directly
  895. // on itself (in other words, not on a prototype).
  896. _.has = function(obj, key) {
  897. return hasOwnProperty.call(obj, key);
  898. };
  899. // Utility Functions
  900. // -----------------
  901. // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  902. // previous owner. Returns a reference to the Underscore object.
  903. _.noConflict = function() {
  904. root._ = previousUnderscore;
  905. return this;
  906. };
  907. // Keep the identity function around for default iterators.
  908. _.identity = function(value) {
  909. return value;
  910. };
  911. // Run a function **n** times.
  912. _.times = function(n, iterator, context) {
  913. var accum = Array(n);
  914. for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
  915. return accum;
  916. };
  917. // Return a random integer between min and max (inclusive).
  918. _.random = function(min, max) {
  919. if (max == null) {
  920. max = min;
  921. min = 0;
  922. }
  923. return min + Math.floor(Math.random() * (max - min + 1));
  924. };
  925. // List of HTML entities for escaping.
  926. var entityMap = {
  927. escape: {
  928. '&': '&amp;',
  929. '<': '&lt;',
  930. '>': '&gt;',
  931. '"': '&quot;',
  932. "'": '&#x27;',
  933. '/': '&#x2F;'
  934. }
  935. };
  936. entityMap.unescape = _.invert(entityMap.escape);
  937. // Regexes containing the keys and values listed immediately above.
  938. var entityRegexes = {
  939. escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
  940. unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
  941. };
  942. // Functions for escaping and unescaping strings to/from HTML interpolation.
  943. _.each(['escape', 'unescape'], function(method) {
  944. _[method] = function(string) {
  945. if (string == null) return '';
  946. return ('' + string).replace(entityRegexes[method], function(match) {
  947. return entityMap[method][match];
  948. });
  949. };
  950. });
  951. // If the value of the named property is a function then invoke it;
  952. // otherwise, return it.
  953. _.result = function(object, property) {
  954. if (object == null) return null;
  955. var value = object[property];
  956. return _.isFunction(value) ? value.call(object) : value;
  957. };
  958. // Add your own custom functions to the Underscore object.
  959. _.mixin = function(obj) {
  960. each(_.functions(obj), function(name){
  961. var func = _[name] = obj[name];
  962. _.prototype[name] = function() {
  963. var args = [this._wrapped];
  964. push.apply(args, arguments);
  965. return result.call(this, func.apply(_, args));
  966. };
  967. });
  968. };
  969. // Generate a unique integer id (unique within the entire client session).
  970. // Useful for temporary DOM ids.
  971. var idCounter = 0;
  972. _.uniqueId = function(prefix) {
  973. var id = ++idCounter + '';
  974. return prefix ? prefix + id : id;
  975. };
  976. // By default, Underscore uses ERB-style template delimiters, change the
  977. // following template settings to use alternative delimiters.
  978. _.templateSettings = {
  979. evaluate : /<%([\s\S]+?)%>/g,
  980. interpolate : /<%=([\s\S]+?)%>/g,
  981. escape : /<%-([\s\S]+?)%>/g
  982. };
  983. // When customizing `templateSettings`, if you don't want to define an
  984. // interpolation, evaluation or escaping regex, we need one that is
  985. // guaranteed not to match.
  986. var noMatch = /(.)^/;
  987. // Certain characters need to be escaped so that they can be put into a
  988. // string literal.
  989. var escapes = {
  990. "'": "'",
  991. '\\': '\\',
  992. '\r': 'r',
  993. '\n': 'n',
  994. '\t': 't',
  995. '\u2028': 'u2028',
  996. '\u2029': 'u2029'
  997. };
  998. var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
  999. // JavaScript micro-templating, similar to John Resig's implementation.
  1000. // Underscore templating handles arbitrary delimiters, preserves whitespace,
  1001. // and correctly escapes quotes within interpolated code.
  1002. _.template = function(text, data, settings) {
  1003. var render;
  1004. settings = _.defaults({}, settings, _.templateSettings);
  1005. // Combine delimiters into one regular expression via alternation.
  1006. var matcher = new RegExp([
  1007. (settings.escape || noMatch).source,
  1008. (settings.interpolate || noMatch).source,
  1009. (settings.evaluate || noMatch).source
  1010. ].join('|') + '|$', 'g');
  1011. // Compile the template source, escaping string literals appropriately.
  1012. var index = 0;
  1013. var source = "__p+='";
  1014. text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
  1015. source += text.slice(index, offset)
  1016. .replace(escaper, function(match) { return '\\' + escapes[match]; });
  1017. if (escape) {
  1018. source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
  1019. }
  1020. if (interpolate) {
  1021. source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
  1022. }
  1023. if (evaluate) {
  1024. source += "';\n" + evaluate + "\n__p+='";
  1025. }
  1026. index = offset + match.length;
  1027. return match;
  1028. });
  1029. source += "';\n";
  1030. // If a variable is not specified, place data values in local scope.
  1031. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
  1032. source = "var __t,__p='',__j=Array.prototype.join," +
  1033. "print=function(){__p+=__j.call(arguments,'');};\n" +
  1034. source + "return __p;\n";
  1035. try {
  1036. render = new Function(settings.variable || 'obj', '_', source);
  1037. } catch (e) {
  1038. e.source = source;
  1039. throw e;
  1040. }
  1041. if (data) return render(data, _);
  1042. var template = function(data) {
  1043. return render.call(this, data, _);
  1044. };
  1045. // Provide the compiled function source as a convenience for precompilation.
  1046. template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
  1047. return template;
  1048. };
  1049. // Add a "chain" function, which will delegate to the wrapper.
  1050. _.chain = function(obj) {
  1051. return _(obj).chain();
  1052. };
  1053. // OOP
  1054. // ---------------
  1055. // If Underscore is called as a function, it returns a wrapped object that
  1056. // can be used OO-style. This wrapper holds altered versions of all the
  1057. // underscore functions. Wrapped objects may be chained.
  1058. // Helper function to continue chaining intermediate results.
  1059. var result = function(obj) {
  1060. return this._chain ? _(obj).chain() : obj;
  1061. };
  1062. // Add all of the Underscore functions to the wrapper object.
  1063. _.mixin(_);
  1064. // Add all mutator Array functions to the wrapper.
  1065. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
  1066. var method = ArrayProto[name];
  1067. _.prototype[name] = function() {
  1068. var obj = this._wrapped;
  1069. method.apply(obj, arguments);
  1070. if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
  1071. return result.call(this, obj);
  1072. };
  1073. });
  1074. // Add all accessor Array functions to the wrapper.
  1075. each(['concat', 'join', 'slice'], function(name) {
  1076. var method = ArrayProto[name];
  1077. _.prototype[name] = function() {
  1078. return result.call(this, method.apply(this._wrapped, arguments));
  1079. };
  1080. });
  1081. _.extend(_.prototype, {
  1082. // Start chaining a wrapped Underscore object.
  1083. chain: function() {
  1084. this._chain = true;
  1085. return this;
  1086. },
  1087. // Extracts the result from a wrapped and chained object.
  1088. value: function() {
  1089. return this._wrapped;
  1090. }
  1091. });
  1092. }).call(this);