stuppid_bot

Untitled

Apr 18th, 2013
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * © All rights reserved x9a.ru, 2013
  3.  */
  4. // %% - %, %s - подставлено значение, %d - приведено к числу и округлено, %f{2} - число с плавающей запятой в скобках количество символов после запятой по-умолчанию 6
  5. // 'Привет, %s!'.format('мир') -> "Привет, мир!"
  6. String.prototype.format = function() {
  7.     var i = 0,
  8.         a = arguments;
  9.     return this.replace(/%(%|s|i|d|f(?:\{(\d+)\})?)/g, function(s, m, l) {
  10.         switch(m[0]) {
  11.             case '%':
  12.                 return '%';
  13.            
  14.             case 's':
  15.                 return a[i++];
  16.            
  17.             case 'i':
  18.             case 'd':          
  19.                 return Math.round(a[i++] * 1);
  20.                
  21.             case 'f':
  22.                 return a[i++].toFixed(l === undefined ? 6 : l) * 1;
  23.         }
  24.     });
  25. }
  26.  
  27. // this.name = 'Вася';
  28. // console.log( 'Привет, ${name}!'.template(this) );
  29. // "Привет, Вася!"
  30. String.prototype.template = function(context) {
  31.     return this.replace(/\$\{(.*?)\}/g, function(s, m) {
  32.         // return context[m] === undefined ? '' : context[m];
  33.         return context[m];
  34.     });
  35. }
  36.  
  37. Array.prototype.shuffle = function() {
  38.     var i = 0,
  39.         j = this.length,
  40.         n,
  41.         swap;
  42.  
  43.     while (i < j) {
  44.         n = Math.floor(Math.random() * j);
  45.         swap = this[n];
  46.         this[n] = this[i];
  47.         this[i++] = swap;
  48.     }
  49. }
  50.  
  51. // [1, 2, 3, 4, 5].rand() -> 4
  52. Array.prototype.rand = function() {
  53.     return this[Math.floor(Math.random() * this.length)];
  54. }
  55.  
  56. if (this.$ === undefined) {
  57.     (function() {
  58.         var cache = {};
  59.  
  60.         $ = function(id) {
  61.             if (!cache[id]) {
  62.                 cache[id] = document.getElementById(id);
  63.             }
  64.  
  65.             return cache[id];
  66.         }
  67.     })();
  68. }
  69.  
  70. function rand(min, max) {
  71.     return min + Math.floor( ++max * Math.random() );
  72. }
  73.  
  74. /**
  75.  * Возвращает размер в байтах в понятном для человека формате.
  76.  *
  77.  * @param size размер в байтах, целое число
  78.  * @param std стандарт, 'SI' | 'IEC'
  79.  * @return string
  80.  */
  81. function formatSize(size, standard) {
  82.     if (standard) {
  83.         standard = standard.toLowerCase();
  84.     }
  85.  
  86.     var n = 0,
  87.         base = standard == 'si' ? 1000 : 1024,
  88.         prefixes = ' KMGTPEZY';
  89.    
  90.     if (size < 1) {
  91.         return 0;
  92.     }
  93.     else if (size >= base) {
  94.         n = Math.floor( Math.log(size) / Math.log(base) );
  95.        
  96.         if (n >= prefixes.length) {
  97.             return 'N/A';
  98.         }
  99.        
  100.         size = ( size / Math.pow(base, n) ).toFixed(2) * 1 + ' ';
  101.     }
  102.    
  103.     return size + prefixes[n] + ( n && standard == 'iec' ? 'i' : '' ) + 'B';
  104. }
  105.  
  106. /**
  107.  * Возвращает продолжительность времени.
  108.  *
  109.  * @param ms миллисекунды
  110.  * @return string
  111.  */
  112. function duration(ms) {
  113.     var hours = ms / 3600000,
  114.         minutes = hours % 1 * 60,
  115.         seconds = Math.round(minutes % 1 * 60);
  116.     minutes = Math.floor(minutes);
  117.     return ( hours >= 1 ? Math.floor(hours) + ':' : '' ) + ( hours >= 1 && minutes < 10 ? '0' + minutes : minutes ) + ':' + ( seconds < 10 ? '0' + seconds : seconds );
  118. }
  119.  
  120. /**
  121.  * Склоняет слово в зависимости от количества.
  122.  *
  123.  * @param count количество
  124.  * @param base основа слова
  125.  * @param singular окончание для ед.ч.
  126.  * @param plural1 1-ое окончание для мн.ч.
  127.  * @param plural2 2-ое окончание для мн.ч.
  128.  * @return string
  129.  */
  130. function pluralize(count, base, singular, plural1, plural2) {
  131.     return count + ' ' + base + ( ( count = (count %= 100) > 20 ? count % 10 : count ) == 0 || count > 4 ? plural2 : count > 1 ? plural1 : singular );
  132. }
  133.  
  134. /**
  135.  * Возвращает продолжительность времени словами.
  136.  *
  137.  * @param ms миллисекунды
  138.  * @return string
  139.  */
  140. // 'Скачивание начнется через ' + durationWords(1.35 * 60000).replace(/(т|д)а/g, '$1у') -> "Скачивание начнется через 1 минуту 21 секунду"
  141. function durationWords(ms) {
  142.     // годов и месяцев нет, так как они имееют разную длительность
  143.     var weeks = ms / 604800000, days = weeks % 1 * 7, hours = days % 1 * 24, minutes = hours % 1 * 60, seconds = minutes % 1 * 60, ret = [];
  144.    
  145.     if (weeks >= 1) {
  146.         ret.push( pluralize( Math.floor(weeks), 'недел', 'я', 'и', 'ь' ) );
  147.     }
  148.    
  149.     if (days >= 1) {
  150.         ret.push( pluralize( Math.floor(days), 'д', 'ень', 'ня', 'ней' ) );
  151.     }
  152.    
  153.     if (hours >= 1) {
  154.         ret.push( pluralize( Math.floor(hours), 'час', '', 'а', 'ов' ) );
  155.     }
  156.    
  157.     if (minutes >= 1) {
  158.         ret.push( pluralize( Math.floor(minutes), 'минут', 'а', 'ы', '' ) );
  159.     }
  160.    
  161.     if (seconds >= 0.5) {
  162.         ret.push( pluralize( Math.round(seconds), 'секунд', 'а', 'ы', '') );
  163.     }
  164.    
  165.     return ret.join(' ');
  166. }
  167.  
  168. // setCookie('test', 'Test', new Date().getTime() + 24 * 3600000);
  169. function setCookie(name, value, expires, path, domain, secure, httponly) {
  170.     document.cookie = name + '=' + encodeURIComponent(value) + (expires === undefined ? '' : '; Expires=' + new Date(expires).toUTCString()) + (path ? '; Path=' + path : '')
  171.         + (domain ? '; Domain=' + domain : '') + (secure ? '; Secure' : '') + (httponly ? '; HttpOnly' : '');
  172. }
  173.  
  174. function deleteCookie(name, path, domain) {
  175.     setCookie(name, '', 0, path, domain);
  176. }
  177.  
  178. querystring = {
  179.     parse: function(str, sep, eq) {
  180.         eq = eq || '=';
  181.         var obj = {};
  182.  
  183.         if (str) {
  184.             var parts = str.split(sep || '&'),
  185.                 i = 0,
  186.                 j = parts.length;
  187.  
  188.             while (i < j) {
  189.                 var temp = parts[i++].split(eq);
  190.  
  191.                 if (temp[0] !== '') {
  192.                     obj[temp[0]] = temp[1] === undefined ? '' : decodeURIComponent(temp[1]);
  193.                 }
  194.             }
  195.         }
  196.  
  197.         return obj;
  198.     },
  199.    
  200.     stringify: function(obj, sep, eq) {
  201.         sep = sep || '&';
  202.         eq = eq || '=';
  203.         var out = [];
  204.  
  205.         for (var i in obj) {
  206.             out.push( i + (obj[i] !== '' ? eq + encodeURIComponent(obj[i]) : '') );
  207.         }
  208.  
  209.         return out.join(sep);
  210.     }
  211. };
  212.  
  213. url = {
  214.     parse: function(str) {
  215.         var parts = /^(?:(\S+):\/\/)?(?:([^:\s]*)(?::(\S*))?@)?(?:([^:/\s]*)(?::(\d*))?)([^?\s]*)?(?:\?([^#\s]*))?(?:#(\S*))?$/.exec(str);
  216.         // console.log(parts);
  217.  
  218.         if (parts !== null) {
  219.             var names = ['scheme', 'user', 'password', 'host', 'port', 'path', 'query', 'hash'],
  220.                 i = 0,
  221.                 j = names.length,
  222.                 obj = {};
  223.  
  224.             while (i < j) {
  225.                 obj[ names[i] ] = parts[++i];
  226.             }
  227.  
  228.             return obj;
  229.         }
  230.  
  231.         return false;
  232.     },
  233.    
  234.     stringify: function(obj) {
  235.         return (obj.scheme ? obj.scheme + '://' : '') + (obj.user ? obj.user + (obj.password ? ':' + obj.password : '') + '@' : '') + (obj.host ? obj.host : '')
  236.         + (obj.port ? ':' + obj.port : '')  + (obj.path ? obj.path : '') + (obj.query ? '?' + obj.query : '') + (obj.hash ? '#' + obj.hash : '');
  237.     }
  238. };
  239.  
  240. // ajax.post('handler.php', {a: 'тест'}, {success: function(data) { console.log(data); }});
  241. ajax = new (function(){
  242.     /* options = {dataType: 'arraybuffer' || 'blob' || 'document' || 'json' || 'text', success: function(data) {...}, fail: function(code, text) {...} } */
  243.     this.plain = function(method, url, params, options) {
  244.         options = options || {};
  245.         var req = new XMLHttpRequest;
  246.         req.responseType = options.dataType || '';
  247.        
  248.         if (options.success || options.fail) {
  249.             req.onreadystatechange = function() {
  250.                 if (req.readyState == 4) {
  251.                     if (req.status >= 200 && req.status < 300) {
  252.                         if (options.success) {
  253.                             options.success(req.response);
  254.                         }
  255.  
  256.                         return;
  257.                     }
  258.  
  259.                     if (options.fail) {
  260.                         options.fail(req.status, req.statusText);
  261.                     }
  262.                 }
  263.             }
  264.         }
  265.  
  266.         req.open(method, url);
  267.  
  268.         if (method.toLowerCase() == 'post') {
  269.             req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  270.             params = querystring.stringify(params);
  271.         }
  272.        
  273.         req.send(params);
  274.      }
  275.  
  276.     this.get = function(url, options) {
  277.         this.plain('GET', url, null, options);
  278.     }
  279.  
  280.     this.post = function(url, params, options) {
  281.         this.plain('POST', url, params, options);
  282.     }
  283. })();
  284.  
  285. query = querystring.parse( location.search.substr(1) ), cookie = querystring.parse(document.cookie, /;\s*/);
Advertisement
Add Comment
Please, Sign In to add comment