underscore-1.3.1.js 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. // Underscore.js 1.3.1
  2. // (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
  3. // Underscore is freely distributable under the MIT license.
  4. // Portions of Underscore are inspired or borrowed from Prototype,
  5. // Oliver Steele's Functional, and John Resig's Micro-Templating.
  6. // For all details and documentation:
  7. // http://documentcloud.github.com/underscore
  8. (function() {
  9. // Baseline setup
  10. // --------------
  11. // Establish the root object, `window` in the browser, or `global` on the server.
  12. var root = this;
  13. // Save the previous value of the `_` variable.
  14. var previousUnderscore = root._;
  15. // Establish the object that gets returned to break out of a loop iteration.
  16. var breaker = {};
  17. // Save bytes in the minified (but not gzipped) version:
  18. var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
  19. // Create quick reference variables for speed access to core prototypes.
  20. var slice = ArrayProto.slice,
  21. unshift = ArrayProto.unshift,
  22. toString = ObjProto.toString,
  23. hasOwnProperty = ObjProto.hasOwnProperty;
  24. // All **ECMAScript 5** native function implementations that we hope to use
  25. // are declared here.
  26. var
  27. nativeForEach = ArrayProto.forEach,
  28. nativeMap = ArrayProto.map,
  29. nativeReduce = ArrayProto.reduce,
  30. nativeReduceRight = ArrayProto.reduceRight,
  31. nativeFilter = ArrayProto.filter,
  32. nativeEvery = ArrayProto.every,
  33. nativeSome = ArrayProto.some,
  34. nativeIndexOf = ArrayProto.indexOf,
  35. nativeLastIndexOf = ArrayProto.lastIndexOf,
  36. nativeIsArray = Array.isArray,
  37. nativeKeys = Object.keys,
  38. nativeBind = FuncProto.bind;
  39. // Create a safe reference to the Underscore object for use below.
  40. var _ = function(obj) { return new wrapper(obj); };
  41. // Export the Underscore object for **Node.js**, with
  42. // backwards-compatibility for the old `require()` API. If we're in
  43. // the browser, add `_` as a global object via a string identifier,
  44. // for Closure Compiler "advanced" mode.
  45. if (typeof exports !== 'undefined') {
  46. if (typeof module !== 'undefined' && module.exports) {
  47. exports = module.exports = _;
  48. }
  49. exports._ = _;
  50. } else {
  51. root['_'] = _;
  52. }
  53. // Current version.
  54. _.VERSION = '1.3.1';
  55. // Collection Functions
  56. // --------------------
  57. // The cornerstone, an `each` implementation, aka `forEach`.
  58. // Handles objects with the built-in `forEach`, arrays, and raw objects.
  59. // Delegates to **ECMAScript 5**'s native `forEach` if available.
  60. var each = _.each = _.forEach = function(obj, iterator, context) {
  61. if (obj == null) return;
  62. if (nativeForEach && obj.forEach === nativeForEach) {
  63. obj.forEach(iterator, context);
  64. } else if (obj.length === +obj.length) {
  65. for (var i = 0, l = obj.length; i < l; i++) {
  66. if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
  67. }
  68. } else {
  69. for (var key in obj) {
  70. if (_.has(obj, key)) {
  71. if (iterator.call(context, obj[key], key, obj) === breaker) return;
  72. }
  73. }
  74. }
  75. };
  76. // Return the results of applying the iterator to each element.
  77. // Delegates to **ECMAScript 5**'s native `map` if available.
  78. _.map = _.collect = function(obj, iterator, context) {
  79. var results = [];
  80. if (obj == null) return results;
  81. if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
  82. each(obj, function(value, index, list) {
  83. results[results.length] = iterator.call(context, value, index, list);
  84. });
  85. if (obj.length === +obj.length) results.length = obj.length;
  86. return results;
  87. };
  88. // **Reduce** builds up a single result from a list of values, aka `inject`,
  89. // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
  90. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
  91. var initial = arguments.length > 2;
  92. if (obj == null) obj = [];
  93. if (nativeReduce && obj.reduce === nativeReduce) {
  94. if (context) iterator = _.bind(iterator, context);
  95. return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
  96. }
  97. each(obj, function(value, index, list) {
  98. if (!initial) {
  99. memo = value;
  100. initial = true;
  101. } else {
  102. memo = iterator.call(context, memo, value, index, list);
  103. }
  104. });
  105. if (!initial) throw new TypeError('Reduce of empty array with no initial value');
  106. return memo;
  107. };
  108. // The right-associative version of reduce, also known as `foldr`.
  109. // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
  110. _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
  111. var initial = arguments.length > 2;
  112. if (obj == null) obj = [];
  113. if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
  114. if (context) iterator = _.bind(iterator, context);
  115. return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
  116. }
  117. var reversed = _.toArray(obj).reverse();
  118. if (context && !initial) iterator = _.bind(iterator, context);
  119. return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);
  120. };
  121. // Return the first value which passes a truth test. Aliased as `detect`.
  122. _.find = _.detect = function(obj, iterator, context) {
  123. var result;
  124. any(obj, function(value, index, list) {
  125. if (iterator.call(context, value, index, list)) {
  126. result = value;
  127. return true;
  128. }
  129. });
  130. return result;
  131. };
  132. // Return all the elements that pass a truth test.
  133. // Delegates to **ECMAScript 5**'s native `filter` if available.
  134. // Aliased as `select`.
  135. _.filter = _.select = function(obj, iterator, context) {
  136. var results = [];
  137. if (obj == null) return results;
  138. if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
  139. each(obj, function(value, index, list) {
  140. if (iterator.call(context, value, index, list)) results[results.length] = value;
  141. });
  142. return results;
  143. };
  144. // Return all the elements for which a truth test fails.
  145. _.reject = function(obj, iterator, context) {
  146. var results = [];
  147. if (obj == null) return results;
  148. each(obj, function(value, index, list) {
  149. if (!iterator.call(context, value, index, list)) results[results.length] = value;
  150. });
  151. return results;
  152. };
  153. // Determine whether all of the elements match a truth test.
  154. // Delegates to **ECMAScript 5**'s native `every` if available.
  155. // Aliased as `all`.
  156. _.every = _.all = function(obj, iterator, context) {
  157. var result = true;
  158. if (obj == null) return result;
  159. if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
  160. each(obj, function(value, index, list) {
  161. if (!(result = result && iterator.call(context, value, index, list))) return breaker;
  162. });
  163. return result;
  164. };
  165. // Determine if at least one element in the object matches a truth test.
  166. // Delegates to **ECMAScript 5**'s native `some` if available.
  167. // Aliased as `any`.
  168. var any = _.some = _.any = function(obj, iterator, context) {
  169. iterator || (iterator = _.identity);
  170. var result = false;
  171. if (obj == null) return result;
  172. if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
  173. each(obj, function(value, index, list) {
  174. if (result || (result = iterator.call(context, value, index, list))) return breaker;
  175. });
  176. return !!result;
  177. };
  178. // Determine if a given value is included in the array or object using `===`.
  179. // Aliased as `contains`.
  180. _.include = _.contains = function(obj, target) {
  181. var found = false;
  182. if (obj == null) return found;
  183. if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
  184. found = any(obj, function(value) {
  185. return value === target;
  186. });
  187. return found;
  188. };
  189. // Invoke a method (with arguments) on every item in a collection.
  190. _.invoke = function(obj, method) {
  191. var args = slice.call(arguments, 2);
  192. return _.map(obj, function(value) {
  193. return (_.isFunction(method) ? method || value : value[method]).apply(value, args);
  194. });
  195. };
  196. // Convenience version of a common use case of `map`: fetching a property.
  197. _.pluck = function(obj, key) {
  198. return _.map(obj, function(value){ return value[key]; });
  199. };
  200. // Return the maximum element or (element-based computation).
  201. _.max = function(obj, iterator, context) {
  202. if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
  203. if (!iterator && _.isEmpty(obj)) return -Infinity;
  204. var result = {computed : -Infinity};
  205. each(obj, function(value, index, list) {
  206. var computed = iterator ? iterator.call(context, value, index, list) : value;
  207. computed >= result.computed && (result = {value : value, computed : computed});
  208. });
  209. return result.value;
  210. };
  211. // Return the minimum element (or element-based computation).
  212. _.min = function(obj, iterator, context) {
  213. if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
  214. if (!iterator && _.isEmpty(obj)) return Infinity;
  215. var result = {computed : Infinity};
  216. each(obj, function(value, index, list) {
  217. var computed = iterator ? iterator.call(context, value, index, list) : value;
  218. computed < result.computed && (result = {value : value, computed : computed});
  219. });
  220. return result.value;
  221. };
  222. // Shuffle an array.
  223. _.shuffle = function(obj) {
  224. var shuffled = [], rand;
  225. each(obj, function(value, index, list) {
  226. if (index == 0) {
  227. shuffled[0] = value;
  228. } else {
  229. rand = Math.floor(Math.random() * (index + 1));
  230. shuffled[index] = shuffled[rand];
  231. shuffled[rand] = value;
  232. }
  233. });
  234. return shuffled;
  235. };
  236. // Sort the object's values by a criterion produced by an iterator.
  237. _.sortBy = function(obj, iterator, context) {
  238. return _.pluck(_.map(obj, function(value, index, list) {
  239. return {
  240. value : value,
  241. criteria : iterator.call(context, value, index, list)
  242. };
  243. }).sort(function(left, right) {
  244. var a = left.criteria, b = right.criteria;
  245. return a < b ? -1 : a > b ? 1 : 0;
  246. }), 'value');
  247. };
  248. // Groups the object's values by a criterion. Pass either a string attribute
  249. // to group by, or a function that returns the criterion.
  250. _.groupBy = function(obj, val) {
  251. var result = {};
  252. var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
  253. each(obj, function(value, index) {
  254. var key = iterator(value, index);
  255. (result[key] || (result[key] = [])).push(value);
  256. });
  257. return result;
  258. };
  259. // Use a comparator function to figure out at what index an object should
  260. // be inserted so as to maintain order. Uses binary search.
  261. _.sortedIndex = function(array, obj, iterator) {
  262. iterator || (iterator = _.identity);
  263. var low = 0, high = array.length;
  264. while (low < high) {
  265. var mid = (low + high) >> 1;
  266. iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
  267. }
  268. return low;
  269. };
  270. // Safely convert anything iterable into a real, live array.
  271. _.toArray = function(iterable) {
  272. if (!iterable) return [];
  273. if (iterable.toArray) return iterable.toArray();
  274. if (_.isArray(iterable)) return slice.call(iterable);
  275. if (_.isArguments(iterable)) return slice.call(iterable);
  276. return _.values(iterable);
  277. };
  278. // Return the number of elements in an object.
  279. _.size = function(obj) {
  280. return _.toArray(obj).length;
  281. };
  282. // Array Functions
  283. // ---------------
  284. // Get the first element of an array. Passing **n** will return the first N
  285. // values in the array. Aliased as `head`. The **guard** check allows it to work
  286. // with `_.map`.
  287. _.first = _.head = function(array, n, guard) {
  288. return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  289. };
  290. // Returns everything but the last entry of the array. Especcialy useful on
  291. // the arguments object. Passing **n** will return all the values in
  292. // the array, excluding the last N. The **guard** check allows it to work with
  293. // `_.map`.
  294. _.initial = function(array, n, guard) {
  295. return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
  296. };
  297. // Get the last element of an array. Passing **n** will return the last N
  298. // values in the array. The **guard** check allows it to work with `_.map`.
  299. _.last = function(array, n, guard) {
  300. if ((n != null) && !guard) {
  301. return slice.call(array, Math.max(array.length - n, 0));
  302. } else {
  303. return array[array.length - 1];
  304. }
  305. };
  306. // Returns everything but the first entry of the array. Aliased as `tail`.
  307. // Especially useful on the arguments object. Passing an **index** will return
  308. // the rest of the values in the array from that index onward. The **guard**
  309. // check allows it to work with `_.map`.
  310. _.rest = _.tail = function(array, index, guard) {
  311. return slice.call(array, (index == null) || guard ? 1 : index);
  312. };
  313. // Trim out all falsy values from an array.
  314. _.compact = function(array) {
  315. return _.filter(array, function(value){ return !!value; });
  316. };
  317. // Return a completely flattened version of an array.
  318. _.flatten = function(array, shallow) {
  319. return _.reduce(array, function(memo, value) {
  320. if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
  321. memo[memo.length] = value;
  322. return memo;
  323. }, []);
  324. };
  325. // Return a version of the array that does not contain the specified value(s).
  326. _.without = function(array) {
  327. return _.difference(array, slice.call(arguments, 1));
  328. };
  329. // Produce a duplicate-free version of the array. If the array has already
  330. // been sorted, you have the option of using a faster algorithm.
  331. // Aliased as `unique`.
  332. _.uniq = _.unique = function(array, isSorted, iterator) {
  333. var initial = iterator ? _.map(array, iterator) : array;
  334. var result = [];
  335. _.reduce(initial, function(memo, el, i) {
  336. if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
  337. memo[memo.length] = el;
  338. result[result.length] = array[i];
  339. }
  340. return memo;
  341. }, []);
  342. return result;
  343. };
  344. // Produce an array that contains the union: each distinct element from all of
  345. // the passed-in arrays.
  346. _.union = function() {
  347. return _.uniq(_.flatten(arguments, true));
  348. };
  349. // Produce an array that contains every item shared between all the
  350. // passed-in arrays. (Aliased as "intersect" for back-compat.)
  351. _.intersection = _.intersect = function(array) {
  352. var rest = slice.call(arguments, 1);
  353. return _.filter(_.uniq(array), function(item) {
  354. return _.every(rest, function(other) {
  355. return _.indexOf(other, item) >= 0;
  356. });
  357. });
  358. };
  359. // Take the difference between one array and a number of other arrays.
  360. // Only the elements present in just the first array will remain.
  361. _.difference = function(array) {
  362. var rest = _.flatten(slice.call(arguments, 1));
  363. return _.filter(array, function(value){ return !_.include(rest, value); });
  364. };
  365. // Zip together multiple lists into a single array -- elements that share
  366. // an index go together.
  367. _.zip = function() {
  368. var args = slice.call(arguments);
  369. var length = _.max(_.pluck(args, 'length'));
  370. var results = new Array(length);
  371. for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
  372. return results;
  373. };
  374. // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
  375. // we need this function. Return the position of the first occurrence of an
  376. // item in an array, or -1 if the item is not included in the array.
  377. // Delegates to **ECMAScript 5**'s native `indexOf` if available.
  378. // If the array is large and already in sort order, pass `true`
  379. // for **isSorted** to use binary search.
  380. _.indexOf = function(array, item, isSorted) {
  381. if (array == null) return -1;
  382. var i, l;
  383. if (isSorted) {
  384. i = _.sortedIndex(array, item);
  385. return array[i] === item ? i : -1;
  386. }
  387. if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
  388. for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i;
  389. return -1;
  390. };
  391. // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
  392. _.lastIndexOf = function(array, item) {
  393. if (array == null) return -1;
  394. if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
  395. var i = array.length;
  396. while (i--) if (i in array && array[i] === item) return i;
  397. return -1;
  398. };
  399. // Generate an integer Array containing an arithmetic progression. A port of
  400. // the native Python `range()` function. See
  401. // [the Python documentation](http://docs.python.org/library/functions.html#range).
  402. _.range = function(start, stop, step) {
  403. if (arguments.length <= 1) {
  404. stop = start || 0;
  405. start = 0;
  406. }
  407. step = arguments[2] || 1;
  408. var len = Math.max(Math.ceil((stop - start) / step), 0);
  409. var idx = 0;
  410. var range = new Array(len);
  411. while(idx < len) {
  412. range[idx++] = start;
  413. start += step;
  414. }
  415. return range;
  416. };
  417. // Function (ahem) Functions
  418. // ------------------
  419. // Reusable constructor function for prototype setting.
  420. var ctor = function(){};
  421. // Create a function bound to a given object (assigning `this`, and arguments,
  422. // optionally). Binding with arguments is also known as `curry`.
  423. // Delegates to **ECMAScript 5**'s native `Function.bind` if available.
  424. // We check for `func.bind` first, to fail fast when `func` is undefined.
  425. _.bind = function bind(func, context) {
  426. var bound, args;
  427. if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
  428. if (!_.isFunction(func)) throw new TypeError;
  429. args = slice.call(arguments, 2);
  430. return bound = function() {
  431. if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
  432. ctor.prototype = func.prototype;
  433. var self = new ctor;
  434. var result = func.apply(self, args.concat(slice.call(arguments)));
  435. if (Object(result) === result) return result;
  436. return self;
  437. };
  438. };
  439. // Bind all of an object's methods to that object. Useful for ensuring that
  440. // all callbacks defined on an object belong to it.
  441. _.bindAll = function(obj) {
  442. var funcs = slice.call(arguments, 1);
  443. if (funcs.length == 0) funcs = _.functions(obj);
  444. each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
  445. return obj;
  446. };
  447. // Memoize an expensive function by storing its results.
  448. _.memoize = function(func, hasher) {
  449. var memo = {};
  450. hasher || (hasher = _.identity);
  451. return function() {
  452. var key = hasher.apply(this, arguments);
  453. return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
  454. };
  455. };
  456. // Delays a function for the given number of milliseconds, and then calls
  457. // it with the arguments supplied.
  458. _.delay = function(func, wait) {
  459. var args = slice.call(arguments, 2);
  460. return setTimeout(function(){ return func.apply(func, args); }, wait);
  461. };
  462. // Defers a function, scheduling it to run after the current call stack has
  463. // cleared.
  464. _.defer = function(func) {
  465. return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
  466. };
  467. // Returns a function, that, when invoked, will only be triggered at most once
  468. // during a given window of time.
  469. _.throttle = function(func, wait) {
  470. var context, args, timeout, throttling, more;
  471. var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
  472. return function() {
  473. context = this; args = arguments;
  474. var later = function() {
  475. timeout = null;
  476. if (more) func.apply(context, args);
  477. whenDone();
  478. };
  479. if (!timeout) timeout = setTimeout(later, wait);
  480. if (throttling) {
  481. more = true;
  482. } else {
  483. func.apply(context, args);
  484. }
  485. whenDone();
  486. throttling = true;
  487. };
  488. };
  489. // Returns a function, that, as long as it continues to be invoked, will not
  490. // be triggered. The function will be called after it stops being called for
  491. // N milliseconds.
  492. _.debounce = function(func, wait) {
  493. var timeout;
  494. return function() {
  495. var context = this, args = arguments;
  496. var later = function() {
  497. timeout = null;
  498. func.apply(context, args);
  499. };
  500. clearTimeout(timeout);
  501. timeout = setTimeout(later, wait);
  502. };
  503. };
  504. // Returns a function that will be executed at most one time, no matter how
  505. // often you call it. Useful for lazy initialization.
  506. _.once = function(func) {
  507. var ran = false, memo;
  508. return function() {
  509. if (ran) return memo;
  510. ran = true;
  511. return memo = func.apply(this, arguments);
  512. };
  513. };
  514. // Returns the first function passed as an argument to the second,
  515. // allowing you to adjust arguments, run code before and after, and
  516. // conditionally execute the original function.
  517. _.wrap = function(func, wrapper) {
  518. return function() {
  519. var args = [func].concat(slice.call(arguments, 0));
  520. return wrapper.apply(this, args);
  521. };
  522. };
  523. // Returns a function that is the composition of a list of functions, each
  524. // consuming the return value of the function that follows.
  525. _.compose = function() {
  526. var funcs = arguments;
  527. return function() {
  528. var args = arguments;
  529. for (var i = funcs.length - 1; i >= 0; i--) {
  530. args = [funcs[i].apply(this, args)];
  531. }
  532. return args[0];
  533. };
  534. };
  535. // Returns a function that will only be executed after being called N times.
  536. _.after = function(times, func) {
  537. if (times <= 0) return func();
  538. return function() {
  539. if (--times < 1) { return func.apply(this, arguments); }
  540. };
  541. };
  542. // Object Functions
  543. // ----------------
  544. // Retrieve the names of an object's properties.
  545. // Delegates to **ECMAScript 5**'s native `Object.keys`
  546. _.keys = nativeKeys || function(obj) {
  547. if (obj !== Object(obj)) throw new TypeError('Invalid object');
  548. var keys = [];
  549. for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
  550. return keys;
  551. };
  552. // Retrieve the values of an object's properties.
  553. _.values = function(obj) {
  554. return _.map(obj, _.identity);
  555. };
  556. // Return a sorted list of the function names available on the object.
  557. // Aliased as `methods`
  558. _.functions = _.methods = function(obj) {
  559. var names = [];
  560. for (var key in obj) {
  561. if (_.isFunction(obj[key])) names.push(key);
  562. }
  563. return names.sort();
  564. };
  565. // Extend a given object with all the properties in passed-in object(s).
  566. _.extend = function(obj) {
  567. each(slice.call(arguments, 1), function(source) {
  568. for (var prop in source) {
  569. obj[prop] = source[prop];
  570. }
  571. });
  572. return obj;
  573. };
  574. // Fill in a given object with default properties.
  575. _.defaults = function(obj) {
  576. each(slice.call(arguments, 1), function(source) {
  577. for (var prop in source) {
  578. if (obj[prop] == null) obj[prop] = source[prop];
  579. }
  580. });
  581. return obj;
  582. };
  583. // Create a (shallow-cloned) duplicate of an object.
  584. _.clone = function(obj) {
  585. if (!_.isObject(obj)) return obj;
  586. return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  587. };
  588. // Invokes interceptor with the obj, and then returns obj.
  589. // The primary purpose of this method is to "tap into" a method chain, in
  590. // order to perform operations on intermediate results within the chain.
  591. _.tap = function(obj, interceptor) {
  592. interceptor(obj);
  593. return obj;
  594. };
  595. // Internal recursive comparison function.
  596. function eq(a, b, stack) {
  597. // Identical objects are equal. `0 === -0`, but they aren't identical.
  598. // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
  599. if (a === b) return a !== 0 || 1 / a == 1 / b;
  600. // A strict comparison is necessary because `null == undefined`.
  601. if (a == null || b == null) return a === b;
  602. // Unwrap any wrapped objects.
  603. if (a._chain) a = a._wrapped;
  604. if (b._chain) b = b._wrapped;
  605. // Invoke a custom `isEqual` method if one is provided.
  606. if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b);
  607. if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a);
  608. // Compare `[[Class]]` names.
  609. var className = toString.call(a);
  610. if (className != toString.call(b)) return false;
  611. switch (className) {
  612. // Strings, numbers, dates, and booleans are compared by value.
  613. case '[object String]':
  614. // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
  615. // equivalent to `new String("5")`.
  616. return a == String(b);
  617. case '[object Number]':
  618. // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
  619. // other numeric values.
  620. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
  621. case '[object Date]':
  622. case '[object Boolean]':
  623. // Coerce dates and booleans to numeric primitive values. Dates are compared by their
  624. // millisecond representations. Note that invalid dates with millisecond representations
  625. // of `NaN` are not equivalent.
  626. return +a == +b;
  627. // RegExps are compared by their source patterns and flags.
  628. case '[object RegExp]':
  629. return a.source == b.source &&
  630. a.global == b.global &&
  631. a.multiline == b.multiline &&
  632. a.ignoreCase == b.ignoreCase;
  633. }
  634. if (typeof a != 'object' || typeof b != 'object') return false;
  635. // Assume equality for cyclic structures. The algorithm for detecting cyclic
  636. // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
  637. var length = stack.length;
  638. while (length--) {
  639. // Linear search. Performance is inversely proportional to the number of
  640. // unique nested structures.
  641. if (stack[length] == a) return true;
  642. }
  643. // Add the first object to the stack of traversed objects.
  644. stack.push(a);
  645. var size = 0, result = true;
  646. // Recursively compare objects and arrays.
  647. if (className == '[object Array]') {
  648. // Compare array lengths to determine if a deep comparison is necessary.
  649. size = a.length;
  650. result = size == b.length;
  651. if (result) {
  652. // Deep compare the contents, ignoring non-numeric properties.
  653. while (size--) {
  654. // Ensure commutative equality for sparse arrays.
  655. if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
  656. }
  657. }
  658. } else {
  659. // Objects with different constructors are not equivalent.
  660. if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false;
  661. // Deep compare objects.
  662. for (var key in a) {
  663. if (_.has(a, key)) {
  664. // Count the expected number of properties.
  665. size++;
  666. // Deep compare each member.
  667. if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break;
  668. }
  669. }
  670. // Ensure that both objects contain the same number of properties.
  671. if (result) {
  672. for (key in b) {
  673. if (_.has(b, key) && !(size--)) break;
  674. }
  675. result = !size;
  676. }
  677. }
  678. // Remove the first object from the stack of traversed objects.
  679. stack.pop();
  680. return result;
  681. }
  682. // Perform a deep comparison to check if two objects are equal.
  683. _.isEqual = function(a, b) {
  684. return eq(a, b, []);
  685. };
  686. // Is a given array, string, or object empty?
  687. // An "empty" object has no enumerable own-properties.
  688. _.isEmpty = function(obj) {
  689. if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
  690. for (var key in obj) if (_.has(obj, key)) return false;
  691. return true;
  692. };
  693. // Is a given value a DOM element?
  694. _.isElement = function(obj) {
  695. return !!(obj && obj.nodeType == 1);
  696. };
  697. // Is a given value an array?
  698. // Delegates to ECMA5's native Array.isArray
  699. _.isArray = nativeIsArray || function(obj) {
  700. return toString.call(obj) == '[object Array]';
  701. };
  702. // Is a given variable an object?
  703. _.isObject = function(obj) {
  704. return obj === Object(obj);
  705. };
  706. // Is a given variable an arguments object?
  707. _.isArguments = function(obj) {
  708. return toString.call(obj) == '[object Arguments]';
  709. };
  710. if (!_.isArguments(arguments)) {
  711. _.isArguments = function(obj) {
  712. return !!(obj && _.has(obj, 'callee'));
  713. };
  714. }
  715. // Is a given value a function?
  716. _.isFunction = function(obj) {
  717. return toString.call(obj) == '[object Function]';
  718. };
  719. // Is a given value a string?
  720. _.isString = function(obj) {
  721. return toString.call(obj) == '[object String]';
  722. };
  723. // Is a given value a number?
  724. _.isNumber = function(obj) {
  725. return toString.call(obj) == '[object Number]';
  726. };
  727. // Is the given value `NaN`?
  728. _.isNaN = function(obj) {
  729. // `NaN` is the only value for which `===` is not reflexive.
  730. return obj !== obj;
  731. };
  732. // Is a given value a boolean?
  733. _.isBoolean = function(obj) {
  734. return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
  735. };
  736. // Is a given value a date?
  737. _.isDate = function(obj) {
  738. return toString.call(obj) == '[object Date]';
  739. };
  740. // Is the given value a regular expression?
  741. _.isRegExp = function(obj) {
  742. return toString.call(obj) == '[object RegExp]';
  743. };
  744. // Is a given value equal to null?
  745. _.isNull = function(obj) {
  746. return obj === null;
  747. };
  748. // Is a given variable undefined?
  749. _.isUndefined = function(obj) {
  750. return obj === void 0;
  751. };
  752. // Has own property?
  753. _.has = function(obj, key) {
  754. return hasOwnProperty.call(obj, key);
  755. };
  756. // Utility Functions
  757. // -----------------
  758. // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  759. // previous owner. Returns a reference to the Underscore object.
  760. _.noConflict = function() {
  761. root._ = previousUnderscore;
  762. return this;
  763. };
  764. // Keep the identity function around for default iterators.
  765. _.identity = function(value) {
  766. return value;
  767. };
  768. // Run a function **n** times.
  769. _.times = function (n, iterator, context) {
  770. for (var i = 0; i < n; i++) iterator.call(context, i);
  771. };
  772. // Escape a string for HTML interpolation.
  773. _.escape = function(string) {
  774. return (''+string).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;');
  775. };
  776. // Add your own custom functions to the Underscore object, ensuring that
  777. // they're correctly added to the OOP wrapper as well.
  778. _.mixin = function(obj) {
  779. each(_.functions(obj), function(name){
  780. addToWrapper(name, _[name] = obj[name]);
  781. });
  782. };
  783. // Generate a unique integer id (unique within the entire client session).
  784. // Useful for temporary DOM ids.
  785. var idCounter = 0;
  786. _.uniqueId = function(prefix) {
  787. var id = idCounter++;
  788. return prefix ? prefix + id : id;
  789. };
  790. // By default, Underscore uses ERB-style template delimiters, change the
  791. // following template settings to use alternative delimiters.
  792. _.templateSettings = {
  793. evaluate : /<%([\s\S]+?)%>/g,
  794. interpolate : /<%=([\s\S]+?)%>/g,
  795. escape : /<%-([\s\S]+?)%>/g
  796. };
  797. // When customizing `templateSettings`, if you don't want to define an
  798. // interpolation, evaluation or escaping regex, we need one that is
  799. // guaranteed not to match.
  800. var noMatch = /.^/;
  801. // Within an interpolation, evaluation, or escaping, remove HTML escaping
  802. // that had been previously added.
  803. var unescape = function(code) {
  804. return code.replace(/\\\\/g, '\\').replace(/\\'/g, "'");
  805. };
  806. // JavaScript micro-templating, similar to John Resig's implementation.
  807. // Underscore templating handles arbitrary delimiters, preserves whitespace,
  808. // and correctly escapes quotes within interpolated code.
  809. _.template = function(str, data) {
  810. var c = _.templateSettings;
  811. var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
  812. 'with(obj||{}){__p.push(\'' +
  813. str.replace(/\\/g, '\\\\')
  814. .replace(/'/g, "\\'")
  815. .replace(c.escape || noMatch, function(match, code) {
  816. return "',_.escape(" + unescape(code) + "),'";
  817. })
  818. .replace(c.interpolate || noMatch, function(match, code) {
  819. return "'," + unescape(code) + ",'";
  820. })
  821. .replace(c.evaluate || noMatch, function(match, code) {
  822. return "');" + unescape(code).replace(/[\r\n\t]/g, ' ') + ";__p.push('";
  823. })
  824. .replace(/\r/g, '\\r')
  825. .replace(/\n/g, '\\n')
  826. .replace(/\t/g, '\\t')
  827. + "');}return __p.join('');";
  828. var func = new Function('obj', '_', tmpl);
  829. if (data) return func(data, _);
  830. return function(data) {
  831. return func.call(this, data, _);
  832. };
  833. };
  834. // Add a "chain" function, which will delegate to the wrapper.
  835. _.chain = function(obj) {
  836. return _(obj).chain();
  837. };
  838. // The OOP Wrapper
  839. // ---------------
  840. // If Underscore is called as a function, it returns a wrapped object that
  841. // can be used OO-style. This wrapper holds altered versions of all the
  842. // underscore functions. Wrapped objects may be chained.
  843. var wrapper = function(obj) { this._wrapped = obj; };
  844. // Expose `wrapper.prototype` as `_.prototype`
  845. _.prototype = wrapper.prototype;
  846. // Helper function to continue chaining intermediate results.
  847. var result = function(obj, chain) {
  848. return chain ? _(obj).chain() : obj;
  849. };
  850. // A method to easily add functions to the OOP wrapper.
  851. var addToWrapper = function(name, func) {
  852. wrapper.prototype[name] = function() {
  853. var args = slice.call(arguments);
  854. unshift.call(args, this._wrapped);
  855. return result(func.apply(_, args), this._chain);
  856. };
  857. };
  858. // Add all of the Underscore functions to the wrapper object.
  859. _.mixin(_);
  860. // Add all mutator Array functions to the wrapper.
  861. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
  862. var method = ArrayProto[name];
  863. wrapper.prototype[name] = function() {
  864. var wrapped = this._wrapped;
  865. method.apply(wrapped, arguments);
  866. var length = wrapped.length;
  867. if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0];
  868. return result(wrapped, this._chain);
  869. };
  870. });
  871. // Add all accessor Array functions to the wrapper.
  872. each(['concat', 'join', 'slice'], function(name) {
  873. var method = ArrayProto[name];
  874. wrapper.prototype[name] = function() {
  875. return result(method.apply(this._wrapped, arguments), this._chain);
  876. };
  877. });
  878. // Start chaining a wrapped Underscore object.
  879. wrapper.prototype.chain = function() {
  880. this._chain = true;
  881. return this;
  882. };
  883. // Extracts the result from a wrapped and chained object.
  884. wrapper.prototype.value = function() {
  885. return this._wrapped;
  886. };
  887. }).call(this);