code_junkie

JavaScript Collection of one-line Useful Functions

Nov 13th, 2011
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.13 KB | None | 0 0
  1. String.prototype.trim = function(){ this.replace( /^s+|s+$/g, '' ); }
  2.  
  3. function sign(x) {
  4. return (x > 0) - (x < 0);
  5. }
  6.  
  7. function isIE() {
  8. return 'v' == 'v';
  9. }
  10.  
  11. function chain(fn) {
  12. return function() {
  13. return fn.apply(this, arguments) || this;
  14. }
  15. }
  16.  
  17. CanvasRenderingContext2D.prototype.fillRect =
  18. chain(CanvasRenderingContext2D.prototype.fillRect);
  19.  
  20. //...
  21.  
  22. ctx.fillRect(0, 0, 10, 10).fillRect(90, 90, 10, 10).fillRect(0, 10, 100, 10);
  23.  
  24. readableNumberLimiter = function (number,limiter)
  25. {
  26. return number.toString().replace(
  27. new RegExp(
  28. "(^\d{"+(number.toString().length%3||-1)+"})(?=\d{3})"),
  29. "$1"+limiter
  30. ).replace(/(d{3})(?=d)/g,"$1"+limiter);
  31. }
  32.  
  33. readableNumberLimiter(12345678,",");
  34.  
  35. "12,345,678"
  36.  
  37. readableNumberLimiter(12345678,".");
  38.  
  39. "12.345.678"
  40.  
  41. readableNumberLimiter(12345678," ");
  42.  
  43. "12 345 678"
  44.  
  45. function clone(obj) {
  46. return typeof obj === 'undefined' ?
  47. this : (clone.prototype = Object(obj), new clone);
  48. }
  49.  
  50. function addCallback(oldFunc, newFunc) {
  51. oldFunc = oldFunc || function () {};
  52. return function () {oldFunc(); newFunc();};
  53. }
  54.  
  55. document.onload = addCallback(window.onLoad, function () {alert("me too!"); });
  56. document.onload = addCallback(window.onLoad, function () {alert("me three!"); });
  57.  
  58. function chain(f1, f2) {
  59. return typeof f1 !== 'function' ? f2 : function() {
  60. var r1 = f1.apply(this, arguments),
  61. r2 = f2.apply(this, arguments);
  62. return typeof r1 === 'undefined' ? r2 : (r1 && r2);
  63. };
  64. }
  65.  
  66. Date.prototype.daysInMonth = function ()
  67. {
  68. var x = 31;
  69. switch (this.getMonth()) //zero-index
  70. {
  71. case 1: x = (this.isLeapYear()? 29 : 28);break;
  72. case 3:
  73. case 5:
  74. case 8:
  75. case 10: x = 30;
  76. }
  77. return x;
  78. };
  79.  
  80. Date.prototype.isLeapYear = function ()
  81. {
  82. var y = this.getFullYear();
  83. return (y%400==0 || (y%100!=0 && y%4==0));
  84. };
  85.  
  86. Date.prototype.unbox = function ()
  87. {
  88. return new Date(this);
  89. }
  90.  
  91. String.prototype.reverse = function ()
  92. {
  93. return this.split('').reverse().join('');
  94. };
  95.  
  96. function coalesce() {
  97. for (var i=0; i<arguments.length; i++) {
  98. if (arguments[i] !== null) {
  99. return arguments[i];
  100. }
  101. }
  102. return null;
  103. }
  104.  
  105. function IsDefined(variable)
  106. {
  107. return !(typeof(window[variable]) == 'undefined');
  108. }
  109.  
  110. /**
  111. * Left-pad a number with zeros so that it's at least the given
  112. * number of characters long
  113. * @param n The number to pad
  114. * @param len The desired length
  115. */
  116. function leftPad(n, len) {
  117. return (new Array(len - String(n).length + 1)).join("0").concat(n);
  118. }
  119.  
  120. alert(leftPad(42, 6)); // Gives "000042"
  121.  
  122. //+ Carlos R. L. Rodrigues
  123. //@ http://jsfromhell.com/array/chunk [rev. #1]
  124.  
  125. function chunk(a, s){
  126. for(var x, i = 0, c = -1, l = a.length, n = []; i < l; i++)
  127. (x = i % s) ? n[c][x] = a[i] : n[++c] = [a[i]];
  128. return n;
  129. }
  130.  
  131. function formatDate(date, fmt) {
  132. return fmt.replace(
  133. /{([^}:]+)(?::(d+))?}/g,
  134. function (s, comp, pad) {
  135. var fn = date["get" + comp];
  136.  
  137. if (fn) {
  138. var v = (fn.call(date) +
  139. (/Month$/.test(comp) ? 1 : 0)).toString();
  140.  
  141. return pad && (pad = pad - v.length)
  142. ? new Array(pad + 1).join("0") + v
  143. : v;
  144. } else {
  145. return s;
  146. }
  147. });
  148. };
  149.  
  150. var now = new Date();
  151.  
  152. alert(formatDate(now, "This is the year {FullYear}"));
  153. // Output: This is the year 2008
  154.  
  155. alert(formatDate(now, "{FullYear}-{Month:2}-{Date:2}"));
  156. // Output: 2008-09-02
  157. alert(formatDate(now, "{Hours:2}:{Minutes:2}:{Seconds:2}.{Milliseconds:3}"));
  158. // Output: 15:47:32.156
  159.  
  160. alert(formatDate(now, "{Hourz} hours {Minutes} minutes"));
  161. // Output: {Hourz} hours 51 minutes
  162.  
  163. alert(formatDate(now, "{FullYear:}));
  164. // Output: {FullYear:}
  165.  
  166. function typeOf(value) {
  167. var type = typeof value;
  168. return type === 'object' ? (value === null ? 'null' :
  169. Object.prototype.toString.call(value).match(/^[object (.*)]$/)[1]) :
  170. type === 'function' ? 'Function' : type;
  171. }
  172.  
  173. function secondstominutes(secs)
  174. {
  175. return ((arguments[1]=(Math.floor(secs/60)))<10?"0":"")+arguments[1]+":"+((arguments[2]=secs%60)<10?"0":"") + arguments[2];
  176. }
  177.  
  178. function sigFigs(n, sig) {
  179. var mult = Math.pow(10,
  180. sig - Math.floor(Math.log(n) / Math.LN10) - 1);
  181. return Math.round(n * mult) / mult;
  182. }
  183.  
  184. alert(sigFigs(1234567, 3)); // Gives 1230000
  185. alert(sigFigs(0.06805, 3)); // Gives 0.0681
  186. alert(sigFigs(5, 3)); // Gives 5
  187.  
  188. String.prototype.replaceAll = function(target, replacement) {
  189. return this.replace(new RegExp(target, "g"), replacement);
  190. };
  191.  
  192. String.prototype.capitalize = function() {
  193. return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  194. };
  195.  
  196. Array.prototype.contains = function(element) {
  197. var i = this.length;
  198. while (i--) {
  199. if (this[i] === element) {
  200. return true;
  201. }
  202. }
  203. return false;
  204. };
  205.  
  206. Array.prototype.clear = function() {
  207. this.length = 0;
  208. };
  209.  
  210. //+ Jonas Raoni Soares Silva
  211. //@ http://jsfromhell.com/array/rotate [rev. #2]
  212.  
  213. rotate = function(a, p){
  214. for(var l = a.length, p = (Math.abs(p) >= l && (p %= l), p < 0 && (p += l), p), i, x; p; p = (Math.ceil(l / p) - 1) * p - l + (l = p))
  215. for(i = l; i > p; x = a[--i], a[i] = a[i - p], a[i - p] = x);
  216. return a;
  217. };
  218.  
  219. function htmlEscape(s) {
  220. return s.replace(/([&<>])/g,
  221. function (c) {
  222. return "&" + {
  223. "&": "amp",
  224. "<": "lt",
  225. ">": "gt"
  226. }[c] + ";";
  227. });
  228. }
  229.  
  230. function removeQueryStringParam(queryString, param) {
  231. return queryString
  232. .replace(
  233. new RegExp("(&?)(?:"
  234. + (param.join ? param.join("|") : param)
  235. + ")=[^&]*&?", "g"),
  236. "$1")
  237. .replace(/([^&?]*)(?:&|?)$/, "$1");
  238. }
  239.  
  240. removeQueryStringParam("foo=1&param2=2&bar=3&param4=4", [ "foo", "bar" ]));
  241. // Results in "param2=2&param4=4"
  242.  
  243. var is_array = function (value) {
  244. return value &&
  245. typeof value === 'object' &&
  246. typeof value.length === 'number' &&
  247. typeof value.splice === 'function' &&
  248. !(value.propertyIsEnumerable('length'));
  249. };
  250.  
  251. Object.prototype.toString.call(obj) === '[object Array]'
  252.  
  253. typeof obj.length === 'number'
  254.  
  255. String.prototype.strip_tags = function() {
  256. return this.replace(/<[^>]+>/gi,"");
  257. }
  258.  
  259. function getElementsByClassName(name, parent){
  260. for(var o = [], n = new RegExp("\b" + name.replace(/([(){}|*+?.,^$[]\])/g, "\$1") + "\b"), l = (parent || document).getElementsByTagName("*"), i = l.length; i--;)
  261. n.test(l[i].className) && (o[o.length] = l[i]);
  262. return o;
  263. }
  264.  
  265. Array.prototype.lpush = function(item) {
  266. this.unshift(item); return this;
  267. }
  268.  
  269. while (cycle)
  270. var foo = arr.lpush(foo).pop();
  271.  
  272. for(var offsetLeft, offsetRight = start % 8, curByte = this.buffer.length - (start >> 3) - 1, lastByte = this.buffer.length + (-(start + length) >> 3), diff = curByte - lastByte, sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[ lastByte++ ] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); diff; sum += shl(this.buffer[lastByte++ ], (diff-- << 3) - offsetRight);
  273.  
  274. (!k || k == 8 ? 1 : (r = /^(.)^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ? r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0] : (l = (f.value += m.substr(l, (r = /[A|9|C|*]/i.exec(m.substr(l))) ? r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
  275.  
  276. return function(x, y, x0, y0){return Math.sqrt((x -= x0) * x + (y -= y0) * y);}(px, py, x, y) > ray ? {x: Math.cos(tg = Math.atan2(py - y, px - x)) * ray + x, y: Math.sin(tg) * ray + y} : {x: px, y: py};
  277.  
  278. // Javascript modulus operator always returning a positive number
  279. Number.prototype.mod = function(n) {
  280. return ((this%n)+n)%n;
  281. }
  282.  
  283. var num = -2;
  284. alert(num % 10); // will output -2
  285.  
  286. var num = -2;
  287. alert(num.mod(10)); // will output 8
  288.  
  289. function dateOK(Y, M, D) {
  290. return D > 0 &&
  291. (D <= [, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][M] ||
  292. D == 29 && M == 2 && Y % 4 == 0 && (Y % 100 > 0 || Y % 400 == 0));
  293. }
  294.  
  295. String.prototype.repeat = function(n){
  296. n=parseInt(n,10)+1;
  297. return n ? Array(n).join(this) : this.toString();
  298. };
  299.  
  300. String.prototype.repeat = function(n){
  301. return n && n.constructor === Number ? Array(n+1).join(this) : this;
  302. }
  303. //Example:
  304. alert(('-').repeat(10)); //=> '----------'
  305.  
  306. Number.prototype.between = function()
  307. { return this>arguments[0] && this<arguments[1]; };
  308. //example
  309. alert((23).between(10,30)); //=> true
  310. alert((23).between(33,40)); //=> false
  311.  
  312. function extractFloat() {
  313. var x = arguments[0].split(/,|./),
  314. x2 = x.join('').replace(new RegExp(x[x.length-1]+'$'),'.'+x[x.length-1]);
  315. return parseFloat(x2);
  316. }
  317. //example:
  318. extractFloat('1,239.4'); //=> 1239.4
  319. extractFloat('1.239,4'); //=> 1239.4
  320. extractFloat('a1.239,b4'); //=> NaN
  321.  
  322. String.prototype.ellipses = function(len) {
  323. return (this.length > len) ? this.substr(0, len) + "..." : this;
  324. }
  325.  
  326. var isMSIE = /*@cc_on!@*/false;
Add Comment
Please, Sign In to add comment