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

/files/underscorejs/1.4.2/underscore.js

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