Advertisement
stuppid_bot

JS Code Snippets

Aug 21st, 2014
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function gi(id) {
  2.     return document.getElementById(id);
  3. }
  4.  
  5. function $(selector, element) {
  6.     element = element || document;
  7.     return element.querySelector(selector);
  8. }
  9.  
  10. function $$(selector, element) {
  11.     element = element || document;
  12.     return element.querySelectorAll(selector);
  13. }
  14.  
  15. function clone(o) {
  16.     if (o == null || typeof o != 'object') {
  17.         return o;
  18.     }
  19.  
  20.     var copy = o.constructor();
  21.  
  22.     for (var i in o) {
  23.         copy[i] = clone(o[i]);
  24.     }
  25.  
  26.     return copy;
  27. }
  28.  
  29. function isElement(o) {
  30.     return o instanceof HTMLElement;
  31. }
  32.  
  33. function isArray(o) {
  34.     return o instanceof Array;
  35. }
  36.  
  37. function isObject(o) {
  38.     return o && o.constructor == Object;
  39. }
  40.  
  41. function val(element, value)  {
  42.     element = isElement(element) ? element : gi(element);
  43.     var prop = element.tagName == 'INPUT' || element.tagName == 'TEXTAREA' ? 'value' : 'innerHTML';
  44.     return arguments.length > 1 ? element[prop] = value : element[prop];
  45. }
  46.  
  47. function rand(min, max) {
  48.     return Math.floor(Math.random() * (max - min + 1) + min);
  49. }
  50.  
  51. // function shuffle(arr) {
  52. //     return arr.sort(function () {
  53. //         return Math.random() - .5;
  54. //     });
  55. // }
  56.  
  57. function shuffle(a) {
  58.     for (var i = 0, j, k; i < a.length; ++i) {
  59.         j = Math.floor(Math.random() * a.length);
  60.         k = a[j];
  61.         a[j] = a[i];
  62.         a[i] = k;
  63.     }
  64.  
  65.     // return a;
  66. }
  67.  
  68. function choice(arr) {
  69.     return arr[Math.floor(Math.random() * arr.length)];
  70. }
  71.  
  72. function randStr(length, chars){
  73.     length = length || 6;
  74.     chars = chars || 'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890';
  75.     var ret = '';
  76.  
  77.     while (length--) {
  78.         ret += chars.charAt(Math.random() * chars.length);
  79.     }
  80.  
  81.     return ret;
  82. }
  83.  
  84. /**
  85.  * Заменяет на HTML-сущности спецсимволы: \&\, \<\, \>\, \"\.
  86.  * @param {string} string
  87.  * @return {string}
  88.  */
  89. function escapeHTML(str) {
  90.     return str.replace(/[&"<>]/g, function (x) {
  91.         return '&' + {'&': 'amp', '"': 'quot', '<': 'lt', '>': 'gt'}[x] + ';';
  92.     });
  93. }
  94.  
  95. /**
  96.  * Экранирует символы: /\/, /'/, /"/.
  97.  * @param {string} str
  98.  * @return {string}
  99.  */
  100. function addSlashes(str) {
  101.     return str.replace(/([\\'"])/g, '\\$1');
  102. }
  103.  
  104. /**
  105.  * Обратная функция для addSlashes.
  106.  * @param {string} str
  107.  * @return {string}
  108.  */
  109. function stripSlashes(str) {
  110.     return str.replace(/\\([\\'"])/g, '$1');
  111. }
  112.  
  113. /**
  114.  * Экранирует специальные символы, используемые в регулярном выражении.
  115.  * @param {string} str
  116.  * @return {string}
  117.  */
  118. function escapePattern(str) {
  119.     return str.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
  120. }
  121.  
  122. /**
  123.  * «Переворачивает» строку.
  124.  * @param {string} str
  125.  * @return {string}
  126.  **/
  127. function reverseStr(str) {
  128.     return str.split(/|/).reverse().join('');
  129. }
  130.  
  131. function repeatStr(str, n) {
  132.     return new Array(++n).join(str);
  133. }
  134.  
  135. function pad(s, len, padder, direction) {
  136.     // len = len || 78;
  137.  
  138.     if (s.length < len) {
  139.         len = len - s.length;
  140.         padder = typeof padder == 'number' || padder ? padder + '' : ' ';
  141.         direction = direction ? direction.toLowerCase() : 'left';
  142.  
  143.         if (direction == 'both') {
  144.             return pad('', Math.floor(len / 2), padder) + s + pad('', Math.ceil(len / 2), padder, 'right');
  145.         }
  146.  
  147.         padder = repeatStr(padder, Math.ceil(len / padder.length)).substr(0, len);
  148.         s = direction == 'right' ? s + padder : padder + s;
  149.     }
  150.  
  151.     return s;
  152. }
  153.  
  154. function rpad(s, len, padder) {
  155.     return pad(s, len, padder, 'right');
  156. }
  157.  
  158. function center(s, len, padder) {
  159.     return pad(s, len, padder, 'both');
  160. }
  161.  
  162. function wrap(text, width, br) {
  163.     var lines, i, re, line, buf, matches, whitespace, word;
  164.     width = arguments.length > 1 ? arguments[1] : 78;
  165.     br = arguments.length > 2 ? arguments[2] : '\n';
  166.     lines = text.split('\n');
  167.  
  168.     for (i = 0; i < lines.length; ++i) {
  169.         re = /(\s*)(\S+)/g;
  170.         line = [];
  171.         buf = '';
  172.  
  173.         while (matches = re.exec(lines[i])) {
  174.             console.log(matches);
  175.             whitespace = matches[1];
  176.             word = matches[2];
  177.  
  178.             if (buf.length + whitespace.length + word.length <= width) {
  179.                 buf += whitespace;
  180.             }
  181.             else if (buf.length) {
  182.                 line.push(buf);
  183.                 buf = '';
  184.             }
  185.          
  186.             buf += word;
  187.         }
  188.  
  189.         line.push(buf);
  190.         lines[i] = line.join(br);
  191.     }
  192.  
  193.     return lines.join('\n');
  194. }
  195.  
  196. function canvasToBlob(canvas, type, quality) {
  197.     var data = canvas.toDataURL(type, quality);
  198.     data = atob(data.substr(data.indexOf(',') + 1));
  199.     var i = data.length;
  200.     var arr = new Uint8Array(i);
  201.  
  202.     while (i--) {
  203.         arr[i] = data.charCodeAt(i);
  204.     }
  205.  
  206.     return new Blob([arr], {type: type});
  207. }
  208.  
  209. /*
  210.  * @example
  211.  * // 0 - Jan
  212.  * alert('Age: ' + getAge(new Date(1988, 3, 20)));
  213.  * @param {Date} birthday
  214.  * @return {number} age  
  215.  **/
  216. function getAge(birthday) {
  217.     var now = new Date();
  218.     var age = now.getYear() - birthday.getYear();
  219.  
  220.     if (now.getMonth() < birthday.getMonth() ||
  221.         (now.getMonth() == birthday.getMonth() &&
  222.             now.getDate() < birthday.getDate())) {
  223.         --age;
  224.     }
  225.  
  226.     return age;
  227. }
  228.  
  229. /**
  230.  * Сохраняет файл по ссылке под определенным именем.
  231.  * @param {string} url Путь до файла на сервере либо Data URI.
  232.  * @param {string} name Имя сохраняемого файла.
  233.  */
  234. function saveFile(url, name) {
  235.     name = name || 'file';
  236.     var link = document.createElement('a');
  237.     link.setAttribute('download', name);
  238.     link.href = url;
  239.  
  240.     link.onclick = function () {
  241.         document.body.removeChild(this);
  242.     };
  243.  
  244.     link.style.display = 'none';  
  245.     document.body.appendChild(link);
  246.     link.click();
  247. }
  248.  
  249. function formatSize(size) {
  250.     // if (typeof(size) != 'number' and size >= 0) {
  251.     //     throw new TypeError('size must be unsigned number');
  252.     // }
  253.  
  254.     var base = 1024;
  255.     var prefixes = 'KMGTPEZY';
  256.     var n = 0;
  257.    
  258.     if (size < 1) {
  259.         return size;
  260.     }
  261.     else if (size >= base) {
  262.         n = Math.floor(Math.log(size) / Math.log(base));
  263.  
  264.         if (n > prefixes.length) {
  265.             throw new Error('size to big');
  266.         }
  267.  
  268.         size = (size / Math.pow(base, n)).toFixed(2) * 1;
  269.     }
  270.    
  271.     return size + ' ' + (n ? prefixes[n] : '') + 'B';
  272. }
  273.  
  274. var ajax = new Function();
  275.  
  276. ajax.getReq = function (m, u, cb) {
  277.     var r = new XMLHttpRequest();
  278.     r.open(m,u);
  279.  
  280.     r.onload = function () {
  281.         typeof cb == 'function' && cb(r);
  282.     };
  283.  
  284.     r.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  285.     return r;
  286. };
  287.  
  288. ajax.get = function (u, cb) {
  289.     var r = this.getReq('GET', u, cb);
  290.     r.send();
  291. };
  292.  
  293. ajax.load = function (u, e) {
  294.     this.get(u, function (r) {
  295.         val(e, r.response);
  296.     });
  297. };
  298.  
  299. ajax.post = function(u, p, cb) {
  300.     var r = this.getReq('POST', u, cb), q = '', k;
  301.     r.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  302.  
  303.     for (k in p) {
  304.         if (p.hasOwnProperty(k)) {
  305.             q += (q.length ? '&': '') + k + '=' + encodeURIComponent(p[k]);
  306.         };
  307.     }
  308.  
  309.     r.send(q);
  310. };
  311.  
  312. ajax.submit = function (e, cb) {
  313.     e = ge(e);
  314.     var r = this.getReq('POST', e.action, cb), fd = new FormData(e);
  315.     r.send(fd);
  316. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement