Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * © All rights reserved x9a.ru, 2013
- */
- // %% - %, %s - подставлено значение, %d - приведено к числу и округлено, %f{2} - число с плавающей запятой в скобках количество символов после запятой по-умолчанию 6
- // 'Привет, %s!'.format('мир') -> "Привет, мир!"
- String.prototype.format = function() {
- var i = 0,
- a = arguments;
- return this.replace(/%(%|s|i|d|f(?:\{(\d+)\})?)/g, function(s, m, l) {
- switch(m[0]) {
- case '%':
- return '%';
- case 's':
- return a[i++];
- case 'i':
- case 'd':
- return Math.round(a[i++] * 1);
- case 'f':
- return a[i++].toFixed(l === undefined ? 6 : l) * 1;
- }
- });
- }
- // this.name = 'Вася';
- // console.log( 'Привет, ${name}!'.template(this) );
- // "Привет, Вася!"
- String.prototype.template = function(context) {
- return this.replace(/\$\{(.*?)\}/g, function(s, m) {
- // return context[m] === undefined ? '' : context[m];
- return context[m];
- });
- }
- Array.prototype.shuffle = function() {
- var i = 0,
- j = this.length,
- n,
- swap;
- while (i < j) {
- n = Math.floor(Math.random() * j);
- swap = this[n];
- this[n] = this[i];
- this[i++] = swap;
- }
- }
- // [1, 2, 3, 4, 5].rand() -> 4
- Array.prototype.rand = function() {
- return this[Math.floor(Math.random() * this.length)];
- }
- if (this.$ === undefined) {
- (function() {
- var cache = {};
- $ = function(id) {
- if (!cache[id]) {
- cache[id] = document.getElementById(id);
- }
- return cache[id];
- }
- })();
- }
- function rand(min, max) {
- return min + Math.floor( ++max * Math.random() );
- }
- /**
- * Возвращает размер в байтах в понятном для человека формате.
- *
- * @param size размер в байтах, целое число
- * @param std стандарт, 'SI' | 'IEC'
- * @return string
- */
- function formatSize(size, standard) {
- if (standard) {
- standard = standard.toLowerCase();
- }
- var n = 0,
- base = standard == 'si' ? 1000 : 1024,
- prefixes = ' KMGTPEZY';
- if (size < 1) {
- return 0;
- }
- else if (size >= base) {
- n = Math.floor( Math.log(size) / Math.log(base) );
- if (n >= prefixes.length) {
- return 'N/A';
- }
- size = ( size / Math.pow(base, n) ).toFixed(2) * 1 + ' ';
- }
- return size + prefixes[n] + ( n && standard == 'iec' ? 'i' : '' ) + 'B';
- }
- /**
- * Возвращает продолжительность времени.
- *
- * @param ms миллисекунды
- * @return string
- */
- function duration(ms) {
- var hours = ms / 3600000,
- minutes = hours % 1 * 60,
- seconds = Math.round(minutes % 1 * 60);
- minutes = Math.floor(minutes);
- return ( hours >= 1 ? Math.floor(hours) + ':' : '' ) + ( hours >= 1 && minutes < 10 ? '0' + minutes : minutes ) + ':' + ( seconds < 10 ? '0' + seconds : seconds );
- }
- /**
- * Склоняет слово в зависимости от количества.
- *
- * @param count количество
- * @param base основа слова
- * @param singular окончание для ед.ч.
- * @param plural1 1-ое окончание для мн.ч.
- * @param plural2 2-ое окончание для мн.ч.
- * @return string
- */
- function pluralize(count, base, singular, plural1, plural2) {
- return count + ' ' + base + ( ( count = (count %= 100) > 20 ? count % 10 : count ) == 0 || count > 4 ? plural2 : count > 1 ? plural1 : singular );
- }
- /**
- * Возвращает продолжительность времени словами.
- *
- * @param ms миллисекунды
- * @return string
- */
- // 'Скачивание начнется через ' + durationWords(1.35 * 60000).replace(/(т|д)а/g, '$1у') -> "Скачивание начнется через 1 минуту 21 секунду"
- function durationWords(ms) {
- // годов и месяцев нет, так как они имееют разную длительность
- var weeks = ms / 604800000, days = weeks % 1 * 7, hours = days % 1 * 24, minutes = hours % 1 * 60, seconds = minutes % 1 * 60, ret = [];
- if (weeks >= 1) {
- ret.push( pluralize( Math.floor(weeks), 'недел', 'я', 'и', 'ь' ) );
- }
- if (days >= 1) {
- ret.push( pluralize( Math.floor(days), 'д', 'ень', 'ня', 'ней' ) );
- }
- if (hours >= 1) {
- ret.push( pluralize( Math.floor(hours), 'час', '', 'а', 'ов' ) );
- }
- if (minutes >= 1) {
- ret.push( pluralize( Math.floor(minutes), 'минут', 'а', 'ы', '' ) );
- }
- if (seconds >= 0.5) {
- ret.push( pluralize( Math.round(seconds), 'секунд', 'а', 'ы', '') );
- }
- return ret.join(' ');
- }
- // setCookie('test', 'Test', new Date().getTime() + 24 * 3600000);
- function setCookie(name, value, expires, path, domain, secure, httponly) {
- document.cookie = name + '=' + encodeURIComponent(value) + (expires === undefined ? '' : '; Expires=' + new Date(expires).toUTCString()) + (path ? '; Path=' + path : '')
- + (domain ? '; Domain=' + domain : '') + (secure ? '; Secure' : '') + (httponly ? '; HttpOnly' : '');
- }
- function deleteCookie(name, path, domain) {
- setCookie(name, '', 0, path, domain);
- }
- querystring = {
- parse: function(str, sep, eq) {
- eq = eq || '=';
- var obj = {};
- if (str) {
- var parts = str.split(sep || '&'),
- i = 0,
- j = parts.length;
- while (i < j) {
- var temp = parts[i++].split(eq);
- if (temp[0] !== '') {
- obj[temp[0]] = temp[1] === undefined ? '' : decodeURIComponent(temp[1]);
- }
- }
- }
- return obj;
- },
- stringify: function(obj, sep, eq) {
- sep = sep || '&';
- eq = eq || '=';
- var out = [];
- for (var i in obj) {
- out.push( i + (obj[i] !== '' ? eq + encodeURIComponent(obj[i]) : '') );
- }
- return out.join(sep);
- }
- };
- url = {
- parse: function(str) {
- var parts = /^(?:(\S+):\/\/)?(?:([^:\s]*)(?::(\S*))?@)?(?:([^:/\s]*)(?::(\d*))?)([^?\s]*)?(?:\?([^#\s]*))?(?:#(\S*))?$/.exec(str);
- // console.log(parts);
- if (parts !== null) {
- var names = ['scheme', 'user', 'password', 'host', 'port', 'path', 'query', 'hash'],
- i = 0,
- j = names.length,
- obj = {};
- while (i < j) {
- obj[ names[i] ] = parts[++i];
- }
- return obj;
- }
- return false;
- },
- stringify: function(obj) {
- return (obj.scheme ? obj.scheme + '://' : '') + (obj.user ? obj.user + (obj.password ? ':' + obj.password : '') + '@' : '') + (obj.host ? obj.host : '')
- + (obj.port ? ':' + obj.port : '') + (obj.path ? obj.path : '') + (obj.query ? '?' + obj.query : '') + (obj.hash ? '#' + obj.hash : '');
- }
- };
- // ajax.post('handler.php', {a: 'тест'}, {success: function(data) { console.log(data); }});
- ajax = new (function(){
- /* options = {dataType: 'arraybuffer' || 'blob' || 'document' || 'json' || 'text', success: function(data) {...}, fail: function(code, text) {...} } */
- this.plain = function(method, url, params, options) {
- options = options || {};
- var req = new XMLHttpRequest;
- req.responseType = options.dataType || '';
- if (options.success || options.fail) {
- req.onreadystatechange = function() {
- if (req.readyState == 4) {
- if (req.status >= 200 && req.status < 300) {
- if (options.success) {
- options.success(req.response);
- }
- return;
- }
- if (options.fail) {
- options.fail(req.status, req.statusText);
- }
- }
- }
- }
- req.open(method, url);
- if (method.toLowerCase() == 'post') {
- req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
- params = querystring.stringify(params);
- }
- req.send(params);
- }
- this.get = function(url, options) {
- this.plain('GET', url, null, options);
- }
- this.post = function(url, params, options) {
- this.plain('POST', url, params, options);
- }
- })();
- query = querystring.parse( location.search.substr(1) ), cookie = querystring.parse(document.cookie, /;\s*/);
Advertisement
Add Comment
Please, Sign In to add comment