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

/ajax/libs//0.3.2/underscore.js

https://gitlab.com/Mirros/cdnjs
JavaScript | 463 lines | 305 code | 61 blank | 97 comment | 70 complexity | 9c0705e6708fba0e58e3e180b3cada7e MD5 | raw file
  1. // Underscore.js
  2. // (c) 2009 Jeremy Ashkenas, DocumentCloud Inc.
  3. // Underscore is freely distributable under the terms of the MIT license.
  4. // Portions of Underscore are inspired by or borrowed from Prototype.js,
  5. // Oliver Steele's Functional, and John Resig's Micro-Templating.
  6. // For all details and documentation:
  7. // http://documentcloud.github.com/underscore/
  8. (function() {
  9. /*------------------------- Baseline setup ---------------------------------*/
  10. // Establish the root object, "window" in the browser, or "global" on the server.
  11. var root = this;
  12. // Save the previous value of the "_" variable.
  13. var previousUnderscore = root._;
  14. // Create a safe reference to the Underscore object for the functions below.
  15. var _ = root._ = {};
  16. // Export the Underscore object for CommonJS.
  17. if (typeof exports !== 'undefined') _ = exports;
  18. // Current version.
  19. _.VERSION = '0.3.2';
  20. /*------------------------ Collection Functions: ---------------------------*/
  21. // The cornerstone, an each implementation.
  22. // Handles objects implementing forEach, each, arrays, and raw objects.
  23. _.each = function(obj, iterator, context) {
  24. var index = 0;
  25. try {
  26. if (obj.forEach) {
  27. obj.forEach(iterator, context);
  28. } else if (obj.length) {
  29. for (var i=0, l = obj.length; i<l; i++) iterator.call(context, obj[i], i, obj);
  30. } else if (obj.each) {
  31. obj.each(function(value) { iterator.call(context, value, index++, obj); });
  32. } else {
  33. for (var key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) {
  34. iterator.call(context, obj[key], key, obj);
  35. }
  36. }
  37. } catch(e) {
  38. if (e != '__break__') throw e;
  39. }
  40. return obj;
  41. };
  42. // Return the results of applying the iterator to each element. Use JavaScript
  43. // 1.6's version of map, if possible.
  44. _.map = function(obj, iterator, context) {
  45. if (obj && obj.map) return obj.map(iterator, context);
  46. var results = [];
  47. _.each(obj, function(value, index, list) {
  48. results.push(iterator.call(context, value, index, list));
  49. });
  50. return results;
  51. };
  52. // Reduce builds up a single result from a list of values. Also known as
  53. // inject, or foldl.
  54. _.reduce = function(obj, memo, iterator, context) {
  55. _.each(obj, function(value, index, list) {
  56. memo = iterator.call(context, memo, value, index, list);
  57. });
  58. return memo;
  59. };
  60. // Return the first value which passes a truth test.
  61. _.detect = function(obj, iterator, context) {
  62. var result;
  63. _.each(obj, function(value, index, list) {
  64. if (iterator.call(context, value, index, list)) {
  65. result = value;
  66. throw '__break__';
  67. }
  68. });
  69. return result;
  70. };
  71. // Return all the elements that pass a truth test. Use JavaScript 1.6's
  72. // filter(), if it exists.
  73. _.select = function(obj, iterator, context) {
  74. if (obj.filter) return obj.filter(iterator, context);
  75. var results = [];
  76. _.each(obj, function(value, index, list) {
  77. iterator.call(context, value, index, list) && results.push(value);
  78. });
  79. return results;
  80. };
  81. // Return all the elements for which a truth test fails.
  82. _.reject = function(obj, iterator, context) {
  83. var results = [];
  84. _.each(obj, function(value, index, list) {
  85. !iterator.call(context, value, index, list) && results.push(value);
  86. });
  87. return results;
  88. };
  89. // Determine whether all of the elements match a truth test. Delegate to
  90. // JavaScript 1.6's every(), if it is present.
  91. _.all = function(obj, iterator, context) {
  92. iterator = iterator || _.identity;
  93. if (obj.every) return obj.every(iterator, context);
  94. var result = true;
  95. _.each(obj, function(value, index, list) {
  96. if (!(result = result && iterator.call(context, value, index, list))) throw '__break__';
  97. });
  98. return result;
  99. };
  100. // Determine if at least one element in the object matches a truth test. Use
  101. // JavaScript 1.6's some(), if it exists.
  102. _.any = function(obj, iterator, context) {
  103. iterator = iterator || _.identity;
  104. if (obj.some) return obj.some(iterator, context);
  105. var result = false;
  106. _.each(obj, function(value, index, list) {
  107. if (result = iterator.call(context, value, index, list)) throw '__break__';
  108. });
  109. return result;
  110. };
  111. // Determine if a given value is included in the array or object,
  112. // based on '==='.
  113. _.include = function(obj, target) {
  114. if (_.isArray(obj)) return _.indexOf(obj, target) != -1;
  115. var found = false;
  116. _.each(obj, function(value) {
  117. if (found = value === target) {
  118. throw '__break__';
  119. }
  120. });
  121. return found;
  122. };
  123. // Invoke a method with arguments on every item in a collection.
  124. _.invoke = function(obj, method) {
  125. var args = _.toArray(arguments).slice(2);
  126. return _.map(obj, function(value) {
  127. return (method ? value[method] : value).apply(value, args);
  128. });
  129. };
  130. // Convenience version of a common use case of map: fetching a property.
  131. _.pluck = function(obj, key) {
  132. return _.map(obj, function(value){ return value[key]; });
  133. };
  134. // Return the maximum item or (item-based computation).
  135. _.max = function(obj, iterator, context) {
  136. if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
  137. var result = {computed : -Infinity};
  138. _.each(obj, function(value, index, list) {
  139. var computed = iterator ? iterator.call(context, value, index, list) : value;
  140. computed >= result.computed && (result = {value : value, computed : computed});
  141. });
  142. return result.value;
  143. };
  144. // Return the minimum element (or element-based computation).
  145. _.min = function(obj, iterator, context) {
  146. if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
  147. var result = {computed : Infinity};
  148. _.each(obj, function(value, index, list) {
  149. var computed = iterator ? iterator.call(context, value, index, list) : value;
  150. computed < result.computed && (result = {value : value, computed : computed});
  151. });
  152. return result.value;
  153. };
  154. // Sort the object's values by a criteria produced by an iterator.
  155. _.sortBy = function(obj, iterator, context) {
  156. return _.pluck(_.map(obj, function(value, index, list) {
  157. return {
  158. value : value,
  159. criteria : iterator.call(context, value, index, list)
  160. };
  161. }).sort(function(left, right) {
  162. var a = left.criteria, b = right.criteria;
  163. return a < b ? -1 : a > b ? 1 : 0;
  164. }), 'value');
  165. };
  166. // Use a comparator function to figure out at what index an object should
  167. // be inserted so as to maintain order. Uses binary search.
  168. _.sortedIndex = function(array, obj, iterator) {
  169. iterator = iterator || _.identity;
  170. var low = 0, high = array.length;
  171. while (low < high) {
  172. var mid = (low + high) >> 1;
  173. iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
  174. }
  175. return low;
  176. };
  177. // Convert anything iterable into a real, live array.
  178. _.toArray = function(iterable) {
  179. if (!iterable) return [];
  180. if (_.isArray(iterable)) return iterable;
  181. return _.map(iterable, function(val){ return val; });
  182. };
  183. // Return the number of elements in an object.
  184. _.size = function(obj) {
  185. return _.toArray(obj).length;
  186. };
  187. /*-------------------------- Array Functions: ------------------------------*/
  188. // Get the first element of an array.
  189. _.first = function(array) {
  190. return array[0];
  191. };
  192. // Get the last element of an array.
  193. _.last = function(array) {
  194. return array[array.length - 1];
  195. };
  196. // Trim out all falsy values from an array.
  197. _.compact = function(array) {
  198. return _.select(array, function(value){ return !!value; });
  199. };
  200. // Return a completely flattened version of an array.
  201. _.flatten = function(array) {
  202. return _.reduce(array, [], function(memo, value) {
  203. if (_.isArray(value)) return memo.concat(_.flatten(value));
  204. memo.push(value);
  205. return memo;
  206. });
  207. };
  208. // Return a version of the array that does not contain the specified value(s).
  209. _.without = function(array) {
  210. var values = array.slice.call(arguments, 0);
  211. return _.select(array, function(value){ return !_.include(values, value); });
  212. };
  213. // Produce a duplicate-free version of the array. If the array has already
  214. // been sorted, you have the option of using a faster algorithm.
  215. _.uniq = function(array, isSorted) {
  216. return _.reduce(array, [], function(memo, el, i) {
  217. if (0 == i || (isSorted ? _.last(memo) != el : !_.include(memo, el))) memo.push(el);
  218. return memo;
  219. });
  220. };
  221. // Produce an array that contains every item shared between all the
  222. // passed-in arrays.
  223. _.intersect = function(array) {
  224. var rest = _.toArray(arguments).slice(1);
  225. return _.select(_.uniq(array), function(item) {
  226. return _.all(rest, function(other) {
  227. return _.indexOf(other, item) >= 0;
  228. });
  229. });
  230. };
  231. // Zip together multiple lists into a single array -- elements that share
  232. // an index go together.
  233. _.zip = function() {
  234. var args = _.toArray(arguments);
  235. var length = _.max(_.pluck(args, 'length'));
  236. var results = new Array(length);
  237. for (var i=0; i<length; i++) results[i] = _.pluck(args, String(i));
  238. return results;
  239. };
  240. // If the browser doesn't supply us with indexOf (I'm looking at you, MSIE),
  241. // we need this function. Return the position of the first occurence of an
  242. // item in an array, or -1 if the item is not included in the array.
  243. _.indexOf = function(array, item) {
  244. if (array.indexOf) return array.indexOf(item);
  245. for (i=0, l=array.length; i<l; i++) if (array[i] === item) return i;
  246. return -1;
  247. };
  248. // Provide JavaScript 1.6's lastIndexOf, delegating to the native function,
  249. // if possible.
  250. _.lastIndexOf = function(array, item) {
  251. if (array.lastIndexOf) return array.lastIndexOf(item);
  252. var i = array.length;
  253. while (i--) if (array[i] === item) return i;
  254. return -1;
  255. };
  256. /* ----------------------- Function Functions: -----------------------------*/
  257. // Create a function bound to a given object (assigning 'this', and arguments,
  258. // optionally). Binding with arguments is also known as 'curry'.
  259. _.bind = function(func, context) {
  260. if (!context) return func;
  261. var args = _.toArray(arguments).slice(2);
  262. return function() {
  263. var a = args.concat(_.toArray(arguments));
  264. return func.apply(context, a);
  265. };
  266. };
  267. // Bind all of an object's methods to that object. Useful for ensuring that
  268. // all callbacks defined on an object belong to it.
  269. _.bindAll = function() {
  270. var args = _.toArray(arguments);
  271. var context = args.pop();
  272. _.each(args, function(methodName) {
  273. context[methodName] = _.bind(context[methodName], context);
  274. });
  275. };
  276. // Delays a function for the given number of milliseconds, and then calls
  277. // it with the arguments supplied.
  278. _.delay = function(func, wait) {
  279. var args = _.toArray(arguments).slice(2);
  280. return setTimeout(function(){ return func.apply(func, args); }, wait);
  281. };
  282. // Defers a function, scheduling it to run after the current call stack has
  283. // cleared.
  284. _.defer = function(func) {
  285. return _.delay.apply(_, [func, 1].concat(_.toArray(arguments).slice(1)));
  286. };
  287. // Returns the first function passed as an argument to the second,
  288. // allowing you to adjust arguments, run code before and after, and
  289. // conditionally execute the original function.
  290. _.wrap = function(func, wrapper) {
  291. return function() {
  292. var args = [func].concat(_.toArray(arguments));
  293. return wrapper.apply(wrapper, args);
  294. };
  295. };
  296. // Returns a function that is the composition of a list of functions, each
  297. // consuming the return value of the function that follows.
  298. _.compose = function() {
  299. var funcs = _.toArray(arguments);
  300. return function() {
  301. for (var i=funcs.length-1; i >= 0; i--) {
  302. arguments = [funcs[i].apply(this, arguments)];
  303. }
  304. return arguments[0];
  305. };
  306. };
  307. /* ------------------------- Object Functions: ---------------------------- */
  308. // Retrieve the names of an object's properties.
  309. _.keys = function(obj) {
  310. return _.map(obj, function(value, key){ return key; });
  311. };
  312. // Retrieve the values of an object's properties.
  313. _.values = function(obj) {
  314. return _.map(obj, _.identity);
  315. };
  316. // Extend a given object with all of the properties in a source object.
  317. _.extend = function(destination, source) {
  318. for (var property in source) destination[property] = source[property];
  319. return destination;
  320. };
  321. // Create a (shallow-cloned) duplicate of an object.
  322. _.clone = function(obj) {
  323. return _.extend({}, obj);
  324. };
  325. // Perform a deep comparison to check if two objects are equal.
  326. _.isEqual = function(a, b) {
  327. // Check object identity.
  328. if (a === b) return true;
  329. // Different types?
  330. var atype = typeof(a), btype = typeof(b);
  331. if (atype != btype) return false;
  332. // Basic equality test (watch out for coercions).
  333. if (a == b) return true;
  334. // One of them implements an isEqual()?
  335. if (a.isEqual) return a.isEqual(b);
  336. // If a is not an object by this point, we can't handle it.
  337. if (atype !== 'object') return false;
  338. // Nothing else worked, deep compare the contents.
  339. var aKeys = _.keys(a), bKeys = _.keys(b);
  340. // Different object sizes?
  341. if (aKeys.length != bKeys.length) return false;
  342. // Recursive comparison of contents.
  343. for (var key in a) if (!_.isEqual(a[key], b[key])) return false;
  344. return true;
  345. };
  346. // Is a given value a DOM element?
  347. _.isElement = function(obj) {
  348. return !!(obj && obj.nodeType == 1);
  349. };
  350. // Is a given value a real Array?
  351. _.isArray = function(obj) {
  352. return Object.prototype.toString.call(obj) == '[object Array]';
  353. };
  354. // Is a given value a Function?
  355. _.isFunction = function(obj) {
  356. return Object.prototype.toString.call(obj) == '[object Function]';
  357. };
  358. // Is a given variable undefined?
  359. _.isUndefined = function(obj) {
  360. return typeof obj == 'undefined';
  361. };
  362. /* -------------------------- Utility Functions: -------------------------- */
  363. // Run Underscore.js in noConflict mode, returning the '_' variable to its
  364. // previous owner. Returns a reference to the Underscore object.
  365. _.noConflict = function() {
  366. root._ = previousUnderscore;
  367. return this;
  368. };
  369. // Keep the identity function around for default iterators.
  370. _.identity = function(value) {
  371. return value;
  372. };
  373. // Generate a unique integer id (unique within the entire client session).
  374. // Useful for temporary DOM ids.
  375. _.uniqueId = function(prefix) {
  376. var id = this._idCounter = (this._idCounter || 0) + 1;
  377. return prefix ? prefix + id : id;
  378. };
  379. // JavaScript templating a-la ERB, pilfered from John Resig's
  380. // "Secrets of the JavaScript Ninja", page 83.
  381. _.template = function(str, data) {
  382. var fn = new Function('obj',
  383. 'var p=[],print=function(){p.push.apply(p,arguments);};' +
  384. 'with(obj){p.push(\'' +
  385. str
  386. .replace(/[\r\t\n]/g, " ")
  387. .split("<%").join("\t")
  388. .replace(/((^|%>)[^\t]*)'/g, "$1\r")
  389. .replace(/\t=(.*?)%>/g, "',$1,'")
  390. .split("\t").join("');")
  391. .split("%>").join("p.push('")
  392. .split("\r").join("\\'")
  393. + "');}return p.join('');");
  394. return data ? fn(data) : fn;
  395. };
  396. /*------------------------------- Aliases ----------------------------------*/
  397. _.forEach = _.each;
  398. _.inject = _.reduce;
  399. _.filter = _.select;
  400. _.every = _.all;
  401. _.some = _.any;
  402. })();