underscore-1.3.3.js 37 KB

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