PageRenderTime 33ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/files/underscorejs/1.6.0/underscore.js

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