PageRenderTime 52ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/files/underscorejs/1.5.2/underscore.js

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