underscore.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. // Underscore.js 1.1.6
  2. // (c) 2011 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 **CommonJS**, with backwards-compatibility
  42. // for the old `require()` API. If we're not in CommonJS, add `_` to the
  43. // global object.
  44. if (typeof module !== 'undefined' && module.exports) {
  45. module.exports = _;
  46. _._ = _;
  47. } else {
  48. root._ = _;
  49. }
  50. // Current version.
  51. _.VERSION = '1.1.6';
  52. // Collection Functions
  53. // --------------------
  54. // The cornerstone, an `each` implementation, aka `forEach`.
  55. // Handles objects implementing `forEach`, arrays, and raw objects.
  56. // Delegates to **ECMAScript 5**'s native `forEach` if available.
  57. var each = _.each = _.forEach = function(obj, iterator, context) {
  58. if (obj == null) return;
  59. if (nativeForEach && obj.forEach === nativeForEach) {
  60. obj.forEach(iterator, context);
  61. } else if (_.isNumber(obj.length)) {
  62. for (var i = 0, l = obj.length; i < l; i++) {
  63. if (iterator.call(context, obj[i], i, obj) === breaker) return;
  64. }
  65. } else {
  66. for (var key in obj) {
  67. if (hasOwnProperty.call(obj, key)) {
  68. if (iterator.call(context, obj[key], key, obj) === breaker) return;
  69. }
  70. }
  71. }
  72. };
  73. // Return the results of applying the iterator to each element.
  74. // Delegates to **ECMAScript 5**'s native `map` if available.
  75. _.map = function(obj, iterator, context) {
  76. var results = [];
  77. if (obj == null) return results;
  78. if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
  79. each(obj, function(value, index, list) {
  80. results[results.length] = iterator.call(context, value, index, list);
  81. });
  82. return results;
  83. };
  84. // **Reduce** builds up a single result from a list of values, aka `inject`,
  85. // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
  86. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
  87. var initial = memo !== void 0;
  88. if (obj == null) obj = [];
  89. if (nativeReduce && obj.reduce === nativeReduce) {
  90. if (context) iterator = _.bind(iterator, context);
  91. return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
  92. }
  93. each(obj, function(value, index, list) {
  94. if (!initial && index === 0) {
  95. memo = value;
  96. initial = true;
  97. } else {
  98. memo = iterator.call(context, memo, value, index, list);
  99. }
  100. });
  101. if (!initial) throw new TypeError("Reduce of empty array with no initial value");
  102. return memo;
  103. };
  104. // The right-associative version of reduce, also known as `foldr`.
  105. // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
  106. _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
  107. if (obj == null) obj = [];
  108. if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
  109. if (context) iterator = _.bind(iterator, context);
  110. return memo !== void 0 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
  111. }
  112. var reversed = (_.isArray(obj) ? obj.slice() : _.toArray(obj)).reverse();
  113. return _.reduce(reversed, iterator, memo, context);
  114. };
  115. // Return the first value which passes a truth test. Aliased as `detect`.
  116. _.find = _.detect = function(obj, iterator, context) {
  117. var result;
  118. any(obj, function(value, index, list) {
  119. if (iterator.call(context, value, index, list)) {
  120. result = value;
  121. return true;
  122. }
  123. });
  124. return result;
  125. };
  126. // Return all the elements that pass a truth test.
  127. // Delegates to **ECMAScript 5**'s native `filter` if available.
  128. // Aliased as `select`.
  129. _.filter = _.select = function(obj, iterator, context) {
  130. var results = [];
  131. if (obj == null) return results;
  132. if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
  133. each(obj, function(value, index, list) {
  134. if (iterator.call(context, value, index, list)) results[results.length] = value;
  135. });
  136. return results;
  137. };
  138. // Return all the elements for which a truth test fails.
  139. _.reject = function(obj, iterator, context) {
  140. var results = [];
  141. if (obj == null) return results;
  142. each(obj, function(value, index, list) {
  143. if (!iterator.call(context, value, index, list)) results[results.length] = value;
  144. });
  145. return results;
  146. };
  147. // Determine whether all of the elements match a truth test.
  148. // Delegates to **ECMAScript 5**'s native `every` if available.
  149. // Aliased as `all`.
  150. _.every = _.all = function(obj, iterator, context) {
  151. var result = true;
  152. if (obj == null) return result;
  153. if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
  154. each(obj, function(value, index, list) {
  155. if (!(result = result && iterator.call(context, value, index, list))) return breaker;
  156. });
  157. return result;
  158. };
  159. // Determine if at least one element in the object matches a truth test.
  160. // Delegates to **ECMAScript 5**'s native `some` if available.
  161. // Aliased as `any`.
  162. var any = _.some = _.any = function(obj, iterator, context) {
  163. iterator || (iterator = _.identity);
  164. var result = false;
  165. if (obj == null) return result;
  166. if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
  167. each(obj, function(value, index, list) {
  168. if (result = iterator.call(context, value, index, list)) return breaker;
  169. });
  170. return result;
  171. };
  172. // Determine if a given value is included in the array or object using `===`.
  173. // Aliased as `contains`.
  174. _.include = _.contains = function(obj, target) {
  175. var found = false;
  176. if (obj == null) return found;
  177. if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
  178. any(obj, function(value) {
  179. if (found = value === target) return true;
  180. });
  181. return found;
  182. };
  183. // Invoke a method (with arguments) on every item in a collection.
  184. _.invoke = function(obj, method) {
  185. var args = slice.call(arguments, 2);
  186. return _.map(obj, function(value) {
  187. return (method.call ? method || value : value[method]).apply(value, args);
  188. });
  189. };
  190. // Convenience version of a common use case of `map`: fetching a property.
  191. _.pluck = function(obj, key) {
  192. return _.map(obj, function(value){ return value[key]; });
  193. };
  194. // Return the maximum element or (element-based computation).
  195. _.max = function(obj, iterator, context) {
  196. if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
  197. var result = {computed : -Infinity};
  198. each(obj, function(value, index, list) {
  199. var computed = iterator ? iterator.call(context, value, index, list) : value;
  200. computed >= result.computed && (result = {value : value, computed : computed});
  201. });
  202. return result.value;
  203. };
  204. // Return the minimum element (or element-based computation).
  205. _.min = function(obj, iterator, context) {
  206. if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
  207. var result = {computed : Infinity};
  208. each(obj, function(value, index, list) {
  209. var computed = iterator ? iterator.call(context, value, index, list) : value;
  210. computed < result.computed && (result = {value : value, computed : computed});
  211. });
  212. return result.value;
  213. };
  214. // Sort the object's values by a criterion produced by an iterator.
  215. _.sortBy = function(obj, iterator, context) {
  216. return _.pluck(_.map(obj, function(value, index, list) {
  217. return {
  218. value : value,
  219. criteria : iterator.call(context, value, index, list)
  220. };
  221. }).sort(function(left, right) {
  222. var a = left.criteria, b = right.criteria;
  223. return a < b ? -1 : a > b ? 1 : 0;
  224. }), 'value');
  225. };
  226. // Use a comparator function to figure out at what index an object should
  227. // be inserted so as to maintain order. Uses binary search.
  228. _.sortedIndex = function(array, obj, iterator) {
  229. iterator || (iterator = _.identity);
  230. var low = 0, high = array.length;
  231. while (low < high) {
  232. var mid = (low + high) >> 1;
  233. iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
  234. }
  235. return low;
  236. };
  237. // Safely convert anything iterable into a real, live array.
  238. _.toArray = function(iterable) {
  239. if (!iterable) return [];
  240. if (iterable.toArray) return iterable.toArray();
  241. if (_.isArray(iterable)) return iterable;
  242. if (_.isArguments(iterable)) return slice.call(iterable);
  243. return _.values(iterable);
  244. };
  245. // Return the number of elements in an object.
  246. _.size = function(obj) {
  247. return _.toArray(obj).length;
  248. };
  249. // Array Functions
  250. // ---------------
  251. // Get the first element of an array. Passing **n** will return the first N
  252. // values in the array. Aliased as `head`. The **guard** check allows it to work
  253. // with `_.map`.
  254. _.first = _.head = function(array, n, guard) {
  255. return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  256. };
  257. // Returns everything but the first entry of the array. Aliased as `tail`.
  258. // Especially useful on the arguments object. Passing an **index** will return
  259. // the rest of the values in the array from that index onward. The **guard**
  260. // check allows it to work with `_.map`.
  261. _.rest = _.tail = function(array, index, guard) {
  262. return slice.call(array, (index == null) || guard ? 1 : index);
  263. };
  264. // Get the last element of an array.
  265. _.last = function(array) {
  266. return array[array.length - 1];
  267. };
  268. // Trim out all falsy values from an array.
  269. _.compact = function(array) {
  270. return _.filter(array, function(value){ return !!value; });
  271. };
  272. // Return a completely flattened version of an array.
  273. _.flatten = function(array) {
  274. return _.reduce(array, function(memo, value) {
  275. if (_.isArray(value)) return memo.concat(_.flatten(value));
  276. memo[memo.length] = value;
  277. return memo;
  278. }, []);
  279. };
  280. // Return a version of the array that does not contain the specified value(s).
  281. _.without = function(array) {
  282. var values = slice.call(arguments, 1);
  283. return _.filter(array, function(value){ return !_.include(values, value); });
  284. };
  285. // Produce a duplicate-free version of the array. If the array has already
  286. // been sorted, you have the option of using a faster algorithm.
  287. // Aliased as `unique`.
  288. _.uniq = _.unique = function(array, isSorted) {
  289. return _.reduce(array, function(memo, el, i) {
  290. if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo[memo.length] = el;
  291. return memo;
  292. }, []);
  293. };
  294. // Produce an array that contains every item shared between all the
  295. // passed-in arrays.
  296. _.intersect = function(array) {
  297. var rest = slice.call(arguments, 1);
  298. return _.filter(_.uniq(array), function(item) {
  299. return _.every(rest, function(other) {
  300. return _.indexOf(other, item) >= 0;
  301. });
  302. });
  303. };
  304. // Zip together multiple lists into a single array -- elements that share
  305. // an index go together.
  306. _.zip = function() {
  307. var args = slice.call(arguments);
  308. var length = _.max(_.pluck(args, 'length'));
  309. var results = new Array(length);
  310. for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
  311. return results;
  312. };
  313. // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
  314. // we need this function. Return the position of the first occurrence of an
  315. // item in an array, or -1 if the item is not included in the array.
  316. // Delegates to **ECMAScript 5**'s native `indexOf` if available.
  317. // If the array is large and already in sort order, pass `true`
  318. // for **isSorted** to use binary search.
  319. _.indexOf = function(array, item, isSorted) {
  320. if (array == null) return -1;
  321. var i, l;
  322. if (isSorted) {
  323. i = _.sortedIndex(array, item);
  324. return array[i] === item ? i : -1;
  325. }
  326. if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
  327. for (i = 0, l = array.length; i < l; i++) if (array[i] === item) return i;
  328. return -1;
  329. };
  330. // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
  331. _.lastIndexOf = function(array, item) {
  332. if (array == null) return -1;
  333. if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
  334. var i = array.length;
  335. while (i--) if (array[i] === item) return i;
  336. return -1;
  337. };
  338. // Generate an integer Array containing an arithmetic progression. A port of
  339. // the native Python `range()` function. See
  340. // [the Python documentation](http://docs.python.org/library/functions.html#range).
  341. _.range = function(start, stop, step) {
  342. if (arguments.length <= 1) {
  343. stop = start || 0;
  344. start = 0;
  345. }
  346. step = arguments[2] || 1;
  347. var len = Math.max(Math.ceil((stop - start) / step), 0);
  348. var idx = 0;
  349. var range = new Array(len);
  350. while(idx < len) {
  351. range[idx++] = start;
  352. start += step;
  353. }
  354. return range;
  355. };
  356. // Function (ahem) Functions
  357. // ------------------
  358. // Create a function bound to a given object (assigning `this`, and arguments,
  359. // optionally). Binding with arguments is also known as `curry`.
  360. // Delegates to **ECMAScript 5**'s native `Function.bind` if available.
  361. // We check for `func.bind` first, to fail fast when `func` is undefined.
  362. _.bind = function(func, obj) {
  363. if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
  364. var args = slice.call(arguments, 2);
  365. return function() {
  366. return func.apply(obj, args.concat(slice.call(arguments)));
  367. };
  368. };
  369. // Bind all of an object's methods to that object. Useful for ensuring that
  370. // all callbacks defined on an object belong to it.
  371. _.bindAll = function(obj) {
  372. var funcs = slice.call(arguments, 1);
  373. if (funcs.length == 0) funcs = _.functions(obj);
  374. each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
  375. return obj;
  376. };
  377. // Memoize an expensive function by storing its results.
  378. _.memoize = function(func, hasher) {
  379. var memo = {};
  380. hasher || (hasher = _.identity);
  381. return function() {
  382. var key = hasher.apply(this, arguments);
  383. return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
  384. };
  385. };
  386. // Delays a function for the given number of milliseconds, and then calls
  387. // it with the arguments supplied.
  388. _.delay = function(func, wait) {
  389. var args = slice.call(arguments, 2);
  390. return setTimeout(function(){ return func.apply(func, args); }, wait);
  391. };
  392. // Defers a function, scheduling it to run after the current call stack has
  393. // cleared.
  394. _.defer = function(func) {
  395. return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
  396. };
  397. // Internal function used to implement `_.throttle` and `_.debounce`.
  398. var limit = function(func, wait, debounce) {
  399. var timeout;
  400. return function() {
  401. var context = this, args = arguments;
  402. var throttler = function() {
  403. timeout = null;
  404. func.apply(context, args);
  405. };
  406. if (debounce) clearTimeout(timeout);
  407. if (debounce || !timeout) timeout = setTimeout(throttler, wait);
  408. };
  409. };
  410. // Returns a function, that, when invoked, will only be triggered at most once
  411. // during a given window of time.
  412. _.throttle = function(func, wait) {
  413. return limit(func, wait, false);
  414. };
  415. // Returns a function, that, as long as it continues to be invoked, will not
  416. // be triggered. The function will be called after it stops being called for
  417. // N milliseconds.
  418. _.debounce = function(func, wait) {
  419. return limit(func, wait, true);
  420. };
  421. // Returns a function that will be executed at most one time, no matter how
  422. // often you call it. Useful for lazy initialization.
  423. _.once = function(func) {
  424. var ran = false, memo;
  425. return function() {
  426. if (ran) return memo;
  427. ran = true;
  428. return memo = func.apply(this, arguments);
  429. };
  430. };
  431. // Returns the first function passed as an argument to the second,
  432. // allowing you to adjust arguments, run code before and after, and
  433. // conditionally execute the original function.
  434. _.wrap = function(func, wrapper) {
  435. return function() {
  436. var args = [func].concat(slice.call(arguments));
  437. return wrapper.apply(this, args);
  438. };
  439. };
  440. // Returns a function that is the composition of a list of functions, each
  441. // consuming the return value of the function that follows.
  442. _.compose = function() {
  443. var funcs = slice.call(arguments);
  444. return function() {
  445. var args = slice.call(arguments);
  446. for (var i=funcs.length-1; i >= 0; i--) {
  447. args = [funcs[i].apply(this, args)];
  448. }
  449. return args[0];
  450. };
  451. };
  452. // Returns a function that will only be executed after being called N times.
  453. _.after = function(times, func) {
  454. return function() {
  455. if (--times < 1) { return func.apply(this, arguments); }
  456. };
  457. };
  458. // Object Functions
  459. // ----------------
  460. // Retrieve the names of an object's properties.
  461. // Delegates to **ECMAScript 5**'s native `Object.keys`
  462. _.keys = nativeKeys || function(obj) {
  463. if (obj !== Object(obj)) throw new TypeError('Invalid object');
  464. var keys = [];
  465. for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key;
  466. return keys;
  467. };
  468. // Retrieve the values of an object's properties.
  469. _.values = function(obj) {
  470. return _.map(obj, _.identity);
  471. };
  472. // Return a sorted list of the function names available on the object.
  473. // Aliased as `methods`
  474. _.functions = _.methods = function(obj) {
  475. return _.filter(_.keys(obj), function(key){ return _.isFunction(obj[key]); }).sort();
  476. };
  477. // Extend a given object with all the properties in passed-in object(s).
  478. _.extend = function(obj) {
  479. each(slice.call(arguments, 1), function(source) {
  480. for (var prop in source) {
  481. if (source[prop] !== void 0) obj[prop] = source[prop];
  482. }
  483. });
  484. return obj;
  485. };
  486. // Fill in a given object with default properties.
  487. _.defaults = function(obj) {
  488. each(slice.call(arguments, 1), function(source) {
  489. for (var prop in source) {
  490. if (obj[prop] == null) obj[prop] = source[prop];
  491. }
  492. });
  493. return obj;
  494. };
  495. // Create a (shallow-cloned) duplicate of an object.
  496. _.clone = function(obj) {
  497. return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  498. };
  499. // Invokes interceptor with the obj, and then returns obj.
  500. // The primary purpose of this method is to "tap into" a method chain, in
  501. // order to perform operations on intermediate results within the chain.
  502. _.tap = function(obj, interceptor) {
  503. interceptor(obj);
  504. return obj;
  505. };
  506. // Perform a deep comparison to check if two objects are equal.
  507. _.isEqual = function(a, b) {
  508. // Check object identity.
  509. if (a === b) return true;
  510. // Different types?
  511. var atype = typeof(a), btype = typeof(b);
  512. if (atype != btype) return false;
  513. // Basic equality test (watch out for coercions).
  514. if (a == b) return true;
  515. // One is falsy and the other truthy.
  516. if ((!a && b) || (a && !b)) return false;
  517. // Unwrap any wrapped objects.
  518. if (a._chain) a = a._wrapped;
  519. if (b._chain) b = b._wrapped;
  520. // One of them implements an isEqual()?
  521. if (a.isEqual) return a.isEqual(b);
  522. // Check dates' integer values.
  523. if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime();
  524. // Both are NaN?
  525. if (_.isNaN(a) && _.isNaN(b)) return false;
  526. // Compare regular expressions.
  527. if (_.isRegExp(a) && _.isRegExp(b))
  528. return a.source === b.source &&
  529. a.global === b.global &&
  530. a.ignoreCase === b.ignoreCase &&
  531. a.multiline === b.multiline;
  532. // If a is not an object by this point, we can't handle it.
  533. if (atype !== 'object') return false;
  534. // Check for different array lengths before comparing contents.
  535. if (a.length && (a.length !== b.length)) return false;
  536. // Nothing else worked, deep compare the contents.
  537. var aKeys = _.keys(a), bKeys = _.keys(b);
  538. // Different object sizes?
  539. if (aKeys.length != bKeys.length) return false;
  540. // Recursive comparison of contents.
  541. for (var key in a) if (!(key in b) || !_.isEqual(a[key], b[key])) return false;
  542. return true;
  543. };
  544. // Is a given array or object empty?
  545. _.isEmpty = function(obj) {
  546. if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
  547. for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
  548. return true;
  549. };
  550. // Is a given value a DOM element?
  551. _.isElement = function(obj) {
  552. return !!(obj && obj.nodeType == 1);
  553. };
  554. // Is a given value an array?
  555. // Delegates to ECMA5's native Array.isArray
  556. _.isArray = nativeIsArray || function(obj) {
  557. return toString.call(obj) === '[object Array]';
  558. };
  559. // Is a given variable an arguments object?
  560. _.isArguments = function(obj) {
  561. return !!(obj && hasOwnProperty.call(obj, 'callee'));
  562. };
  563. // Is a given value a function?
  564. _.isFunction = function(obj) {
  565. return !!(obj && obj.constructor && obj.call && obj.apply);
  566. };
  567. // Is a given value a string?
  568. _.isString = function(obj) {
  569. return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
  570. };
  571. // Is a given value a number?
  572. _.isNumber = function(obj) {
  573. return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed));
  574. };
  575. // Is the given value `NaN`? `NaN` happens to be the only value in JavaScript
  576. // that does not equal itself.
  577. _.isNaN = function(obj) {
  578. return obj !== obj;
  579. };
  580. // Is a given value a boolean?
  581. _.isBoolean = function(obj) {
  582. return obj === true || obj === false;
  583. };
  584. // Is a given value a date?
  585. _.isDate = function(obj) {
  586. return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear);
  587. };
  588. // Is the given value a regular expression?
  589. _.isRegExp = function(obj) {
  590. return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
  591. };
  592. // Is a given value equal to null?
  593. _.isNull = function(obj) {
  594. return obj === null;
  595. };
  596. // Is a given variable undefined?
  597. _.isUndefined = function(obj) {
  598. return obj === void 0;
  599. };
  600. // Utility Functions
  601. // -----------------
  602. // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  603. // previous owner. Returns a reference to the Underscore object.
  604. _.noConflict = function() {
  605. root._ = previousUnderscore;
  606. return this;
  607. };
  608. // Keep the identity function around for default iterators.
  609. _.identity = function(value) {
  610. return value;
  611. };
  612. // Run a function **n** times.
  613. _.times = function (n, iterator, context) {
  614. for (var i = 0; i < n; i++) iterator.call(context, i);
  615. };
  616. // Add your own custom functions to the Underscore object, ensuring that
  617. // they're correctly added to the OOP wrapper as well.
  618. _.mixin = function(obj) {
  619. each(_.functions(obj), function(name){
  620. addToWrapper(name, _[name] = obj[name]);
  621. });
  622. };
  623. // Generate a unique integer id (unique within the entire client session).
  624. // Useful for temporary DOM ids.
  625. var idCounter = 0;
  626. _.uniqueId = function(prefix) {
  627. var id = idCounter++;
  628. return prefix ? prefix + id : id;
  629. };
  630. // By default, Underscore uses ERB-style template delimiters, change the
  631. // following template settings to use alternative delimiters.
  632. _.templateSettings = {
  633. evaluate : /<%([\s\S]+?)%>/g,
  634. interpolate : /<%=([\s\S]+?)%>/g
  635. };
  636. // JavaScript micro-templating, similar to John Resig's implementation.
  637. // Underscore templating handles arbitrary delimiters, preserves whitespace,
  638. // and correctly escapes quotes within interpolated code.
  639. _.template = function(str, data) {
  640. var c = _.templateSettings;
  641. var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
  642. 'with(obj||{}){__p.push(\'' +
  643. str.replace(/\\/g, '\\\\')
  644. .replace(/'/g, "\\'")
  645. .replace(c.interpolate, function(match, code) {
  646. return "'," + code.replace(/\\'/g, "'") + ",'";
  647. })
  648. .replace(c.evaluate || null, function(match, code) {
  649. return "');" + code.replace(/\\'/g, "'")
  650. .replace(/[\r\n\t]/g, ' ') + "__p.push('";
  651. })
  652. .replace(/\r/g, '\\r')
  653. .replace(/\n/g, '\\n')
  654. .replace(/\t/g, '\\t')
  655. + "');}return __p.join('');";
  656. var func = new Function('obj', tmpl);
  657. return data ? func(data) : func;
  658. };
  659. // The OOP Wrapper
  660. // ---------------
  661. // If Underscore is called as a function, it returns a wrapped object that
  662. // can be used OO-style. This wrapper holds altered versions of all the
  663. // underscore functions. Wrapped objects may be chained.
  664. var wrapper = function(obj) { this._wrapped = obj; };
  665. // Expose `wrapper.prototype` as `_.prototype`
  666. _.prototype = wrapper.prototype;
  667. // Helper function to continue chaining intermediate results.
  668. var result = function(obj, chain) {
  669. return chain ? _(obj).chain() : obj;
  670. };
  671. // A method to easily add functions to the OOP wrapper.
  672. var addToWrapper = function(name, func) {
  673. wrapper.prototype[name] = function() {
  674. var args = slice.call(arguments);
  675. unshift.call(args, this._wrapped);
  676. return result(func.apply(_, args), this._chain);
  677. };
  678. };
  679. // Add all of the Underscore functions to the wrapper object.
  680. _.mixin(_);
  681. // Add all mutator Array functions to the wrapper.
  682. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
  683. var method = ArrayProto[name];
  684. wrapper.prototype[name] = function() {
  685. method.apply(this._wrapped, arguments);
  686. return result(this._wrapped, this._chain);
  687. };
  688. });
  689. // Add all accessor Array functions to the wrapper.
  690. each(['concat', 'join', 'slice'], function(name) {
  691. var method = ArrayProto[name];
  692. wrapper.prototype[name] = function() {
  693. return result(method.apply(this._wrapped, arguments), this._chain);
  694. };
  695. });
  696. // Start chaining a wrapped Underscore object.
  697. wrapper.prototype.chain = function() {
  698. this._chain = true;
  699. return this;
  700. };
  701. // Extracts the result from a wrapped and chained object.
  702. wrapper.prototype.value = function() {
  703. return this._wrapped;
  704. };
  705. })();