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

/ajax/libs//0.2.0/underscore.js

https://gitlab.com/Mirros/cdnjs
JavaScript | 460 lines | 309 code | 60 blank | 91 comment | 74 complexity | 57d6bd674e13a0657f706c1c26f506f1 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. var root = (typeof window != 'undefined') ? window : exports;
  10. var previousUnderscore = root._;
  11. var _ = root._ = {};
  12. _.VERSION = '0.2.0';
  13. /*------------------------ Collection Functions: ---------------------------*/
  14. // The cornerstone, an each implementation.
  15. // Handles objects implementing forEach, each, arrays, and raw objects.
  16. _.each = function(obj, iterator, context) {
  17. var index = 0;
  18. try {
  19. if (obj.forEach) {
  20. obj.forEach(iterator, context);
  21. } else if (obj.length) {
  22. for (var i=0; i<obj.length; i++) iterator.call(context, obj[i], i);
  23. } else if (obj.each) {
  24. obj.each(function(value) { iterator.call(context, value, index++); });
  25. } else {
  26. var i = 0;
  27. for (var key in obj) {
  28. var value = obj[key], pair = [key, value];
  29. pair.key = key;
  30. pair.value = value;
  31. iterator.call(context, pair, i++);
  32. }
  33. }
  34. } catch(e) {
  35. if (e != '__break__') throw e;
  36. }
  37. return obj;
  38. };
  39. // Return the results of applying the iterator to each element. Use Javascript
  40. // 1.6's version of map, if possible.
  41. _.map = function(obj, iterator, context) {
  42. if (obj && obj.map) return obj.map(iterator, context);
  43. var results = [];
  44. _.each(obj, function(value, index) {
  45. results.push(iterator.call(context, value, index));
  46. });
  47. return results;
  48. };
  49. // Reduce builds up a single result from a list of values. Also known as
  50. // inject, or foldl.
  51. _.reduce = function(obj, memo, iterator, context) {
  52. _.each(obj, function(value, index) {
  53. memo = iterator.call(context, memo, value, index);
  54. });
  55. return memo;
  56. };
  57. // Return the first value which passes a truth test.
  58. _.detect = function(obj, iterator, context) {
  59. var result;
  60. _.each(obj, function(value, index) {
  61. if (iterator.call(context, value, index)) {
  62. result = value;
  63. throw '__break__';
  64. }
  65. });
  66. return result;
  67. };
  68. // Return all the elements that pass a truth test. Use Javascript 1.6's
  69. // filter(), if it exists.
  70. _.select = function(obj, iterator, context) {
  71. if (obj.filter) return obj.filter(iterator, context);
  72. var results = [];
  73. _.each(obj, function(value, index) {
  74. if (iterator.call(context, value, index)) results.push(value);
  75. });
  76. return results;
  77. };
  78. // Return all the elements for which a truth test fails.
  79. _.reject = function(obj, iterator, context) {
  80. var results = [];
  81. _.each(obj, function(value, index) {
  82. if (!iterator.call(context, value, index)) results.push(value);
  83. });
  84. return results;
  85. };
  86. // Determine whether all of the elements match a truth test. Delegate to
  87. // Javascript 1.6's every(), if it is present.
  88. _.all = function(obj, iterator, context) {
  89. iterator = iterator || function(v){ return v; };
  90. if (obj.every) return obj.every(iterator, context);
  91. var result = true;
  92. _.each(obj, function(value, index) {
  93. result = result && !!iterator.call(context, value, index);
  94. if (!result) throw '__break__';
  95. });
  96. return result;
  97. };
  98. // Determine if at least one element in the object matches a truth test. Use
  99. // Javascript 1.6's some(), if it exists.
  100. _.any = function(obj, iterator, context) {
  101. iterator = iterator || function(v) { return v; };
  102. if (obj.some) return obj.some(iterator, context);
  103. var result = false;
  104. _.each(obj, function(value, index) {
  105. if (result = !!iterator.call(context, value, index)) throw '__break__';
  106. });
  107. return result;
  108. };
  109. // Determine if a given value is included in the array or object,
  110. // based on '==='.
  111. _.include = function(obj, target) {
  112. if (_.isArray(obj)) return _.indexOf(obj, target) != -1;
  113. var found = false;
  114. _.each(obj, function(pair) {
  115. if (pair.value === target) {
  116. found = true;
  117. throw '__break__';
  118. }
  119. });
  120. return found;
  121. };
  122. // Invoke a method with arguments on every item in a collection.
  123. _.invoke = function(obj, method) {
  124. var args = _.toArray(arguments).slice(2);
  125. return _.map(obj, function(value) {
  126. return (method ? value[method] : value).apply(value, args);
  127. });
  128. };
  129. // Optimized version of a common use case of map: fetching a property.
  130. _.pluck = function(obj, key) {
  131. var results = [];
  132. _.each(obj, function(value){ results.push(value[key]); });
  133. return results;
  134. };
  135. // Return the maximum item or (item-based computation).
  136. _.max = function(obj, iterator, context) {
  137. if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
  138. var result;
  139. _.each(obj, function(value, index) {
  140. var computed = iterator ? iterator.call(context, value, index) : value;
  141. if (result == null || computed >= result.computed) result = {value : value, computed : computed};
  142. });
  143. return result.value;
  144. };
  145. // Return the minimum element (or element-based computation).
  146. _.min = function(obj, iterator, context) {
  147. if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
  148. var result;
  149. _.each(obj, function(value, index) {
  150. var computed = iterator ? iterator.call(context, value, index) : value;
  151. if (result == null || computed < result.computed) result = {value : value, computed : computed};
  152. });
  153. return result.value;
  154. };
  155. // Sort the object's values by a criteria produced by an iterator.
  156. _.sortBy = function(obj, iterator, context) {
  157. return _.pluck(_.map(obj, function(value, index) {
  158. return {
  159. value : value,
  160. criteria : iterator.call(context, value, index)
  161. };
  162. }).sort(function(left, right) {
  163. var a = left.criteria, b = right.criteria;
  164. return a < b ? -1 : a > b ? 1 : 0;
  165. }), 'value');
  166. };
  167. // Use a comparator function to figure out at what index an object should
  168. // be inserted so as to maintain order. Uses binary search.
  169. _.sortedIndex = function(array, obj, iterator) {
  170. iterator = iterator || function(val) { return val; };
  171. var low = 0, high = array.length;
  172. while (low < high) {
  173. var mid = (low + high) >> 1;
  174. iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
  175. }
  176. return low;
  177. };
  178. // Convert anything iterable into a real, live array.
  179. _.toArray = function(iterable) {
  180. if (!iterable) return [];
  181. if (_.isArray(iterable)) return iterable;
  182. return _.map(iterable, function(val){ return val; });
  183. };
  184. // Return the number of elements in an object.
  185. _.size = function(obj) {
  186. return _.toArray(obj).length;
  187. };
  188. /*-------------------------- Array Functions: ------------------------------*/
  189. // Get the first element of an array.
  190. _.first = function(array) {
  191. return array[0];
  192. };
  193. // Get the last element of an array.
  194. _.last = function(array) {
  195. return array[array.length - 1];
  196. };
  197. // Trim out all falsy values from an array.
  198. _.compact = function(array) {
  199. return _.select(array, function(value){ return !!value; });
  200. };
  201. // Return a completely flattened version of an array.
  202. _.flatten = function(array) {
  203. return _.reduce(array, [], function(memo, value) {
  204. if (_.isArray(value)) return memo.concat(_.flatten(value));
  205. memo.push(value);
  206. return memo;
  207. });
  208. };
  209. // Return a version of the array that does not contain the specified value(s).
  210. _.without = function(array) {
  211. var values = array.slice.call(arguments, 0);
  212. return _.select(array, function(value){ return !_.include(values, value); });
  213. };
  214. // Produce a duplicate-free version of the array. If the array has already
  215. // been sorted, you have the option of using a faster algorithm.
  216. _.uniq = function(array, isSorted) {
  217. return _.reduce(array, [], function(memo, el, i) {
  218. if (0 == i || (isSorted ? _.last(memo) != el : !_.include(memo, el))) memo.push(el);
  219. return memo;
  220. });
  221. };
  222. // Produce an array that contains every item shared between all the
  223. // passed-in arrays.
  224. _.intersect = function(array) {
  225. var rest = _.toArray(arguments).slice(1);
  226. return _.select(_.uniq(array), function(item) {
  227. return _.all(rest, function(other) {
  228. return _.indexOf(other, item) >= 0;
  229. });
  230. });
  231. };
  232. // Zip together multiple lists into a single array -- elements that share
  233. // an index go together.
  234. _.zip = function() {
  235. var args = _.toArray(arguments);
  236. var length = _.max(_.pluck(args, 'length'));
  237. var results = new Array(length);
  238. for (var i=0; i<length; i++) results[i] = _.pluck(args, String(i));
  239. return results;
  240. };
  241. // If the browser doesn't supply us with indexOf (I'm looking at you, MSIE),
  242. // we need this function. Return the position of the first occurence of an
  243. // item in an array, or -1 if the item is not included in the array.
  244. _.indexOf = function(array, item) {
  245. if (array.indexOf) return array.indexOf(item);
  246. for (i=0; i<array.length; i++) if (array[i] === item) return i;
  247. return -1;
  248. };
  249. // Provide Javascript 1.6's lastIndexOf, delegating to the native function,
  250. // if possible.
  251. _.lastIndexOf = function(array, item) {
  252. if (array.lastIndexOf) return array.lastIndexOf(item);
  253. for (i=array.length - 1; i>=0; 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 _.pluck(obj, 'key');
  311. };
  312. // Retrieve the values of an object's properties.
  313. _.values = function(obj) {
  314. return _.pluck(obj, 'value');
  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 typeof obj == '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. // Generate a unique integer id (unique within the entire client session).
  370. // Useful for temporary DOM ids.
  371. _.uniqueId = function(prefix) {
  372. var id = this._idCounter = (this._idCounter || 0) + 1;
  373. return prefix ? prefix + id : id;
  374. };
  375. // Javascript templating a-la ERB, pilfered from John Resig's
  376. // "Secrets of the Javascript Ninja", page 83.
  377. _.template = function(str, data) {
  378. var fn = new Function('obj',
  379. 'var p=[],print=function(){p.push.apply(p,arguments);};' +
  380. 'with(obj){p.push(\'' +
  381. str
  382. .replace(/[\r\t\n]/g, " ")
  383. .split("<%").join("\t")
  384. .replace(/((^|%>)[^\t]*)'/g, "$1\r")
  385. .replace(/\t=(.*?)%>/g, "',$1,'")
  386. .split("\t").join("');")
  387. .split("%>").join("p.push('")
  388. .split("\r").join("\\'")
  389. + "');}return p.join('');");
  390. return data ? fn(data) : fn;
  391. };
  392. /*------------------------------- Aliases ----------------------------------*/
  393. _.forEach = _.each;
  394. _.inject = _.reduce;
  395. _.filter = _.select;
  396. _.every = _.all;
  397. _.some = _.any;
  398. /*------------------------- Export for ServerJS ----------------------------*/
  399. if (!_.isUndefined(exports)) exports = _;
  400. })();