PageRenderTime 30ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/files/underscorejs/1.4.4/underscore.js

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