PageRenderTime 59ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/ajax/libs//1.5.0/underscore.js

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