PageRenderTime 49ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/ajax/libs//0.1.1/underscore.js

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