Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- © All rights reserved x9a.ru, 2013
- порядковые имена переменных:
- var, var1, var2
- краткие имена переменных:
- b - булев
- n - число
- s - строка
- o - обьект
- a - массив
- p - property
- e - error
- m - match
- l - length
- k - key
- v - value
- t - time
- ts - timestamp
- dt - datetime
- re - regExp
- el - element
- ev - event
- fn - function
- cb - callback
- im, img - image
- dst - destination
- src - source
- txt - text
- ctx - context
- out
- htm, html
- opts - options
- data
- temp - temporary
- i, j, k - счетчики
- преффиксы функций: get, load, add, delete, remove, update
- побитовые аналоги:
- x | 0 == x >> 0 == Math.floor(x)
- x + (x <= 0 ? 0 : 1) | 0 == Math.ceil(x)
- x + (x < 0 ? -.5 : .5) | 0 == Math.round(x)
- 1 << x == Math.pow(2, x)
- */
- Object.values = function(o) {
- var a = [];
- for (var p in o) {
- if ( o.hasOwnProperty(p) ) {
- a.push(o[p]);
- }
- }
- return a;
- };
- String.prototype.repeat = function(n) {
- return new Array(++n).join(this);
- };
- String.prototype.pad = function(requiredLength, paddingStr, paddingType) {
- var n = requiredLength - this.length;
- if (n > 0) {
- paddingType = paddingType ? paddingType.toLowerCase() : '';
- paddingStr = paddingStr || ' ';
- paddingStr = paddingStr.repeat( Math.ceil(n / paddingStr.length) ).substr(0, n);
- if (paddingType == 'both') {
- n /= 2;
- return paddingStr.substr( 0, Math.ceil(n) ) + this + paddingStr.substr( 0, Math.floor(n) );
- }
- if (paddingType == 'left') {
- return paddingStr + this;
- }
- return this + paddingStr;
- }
- return this + '';
- };
- // синтаксис аналогичен printf
- // 'Привет, %s!'.format('мир') -> "Привет, мир!"
- // '%.1s.%.1s. %s'.format('Иван', 'Иванович', 'Иванов') -> "И.И. Иванов"
- // http://ru.wikipedia.org/wiki/Printf
- ( function() {
- function addPlus(n, flags) {
- return (n > 0 && flags && /\+/.test(flags) ? '+' : '') + n;
- };
- String.prototype.format = function() {
- var q = 0, w = arguments, e;
- return this.replace(/%(?:%|([-+0]+)?([1-9]\d*)?(?:\.([1-9]\d*))?([a-z]))/gi, function(m, flags, width, precision, type) {
- if (m == '%%') {
- return '%';
- }
- e = w[q++];
- switch (type) {
- case 'd':
- e = addPlus( Math.round(e), flags );
- break;
- case 'f':
- e = addPlus( e.toFixed(precision || 6), flags );
- break;
- case 's':
- e += '';
- e = precision ? e.substr(0, precision) : e;
- break;
- default:
- return m;
- }
- if (width) {
- e = e.pad( width, /0/.test(flags) ? '0' : ' ', /-/.test(flags) ? 'right' : 'left' );
- }
- return e;
- });
- };
- } )();
- // this.name = 'Вася';
- // console.log( 'Привет, ${name}!'.template(this) );
- // "Привет, Вася!"
- String.prototype.template = function(context) {
- return this.replace(/\$\{(.*?)\}/g, function(match, name) {
- return context[name];
- });
- };
- ( function() {
- var entities = {'<': 'lt', '>': 'gt', '&': 'amp'},
- re = new RegExp('[' + Object.keys(entities).join('') + ']', 'g');
- String.prototype.escape = function() {
- return this.replace(re, function(m) {
- return '&' + entities[m] + ';';
- });
- }
- } )();
- String.prototype.addslashes = function() {
- return this.replace(/([\\'"])/g, '\\$1');
- };
- String.prototype.stripslashes = function() {
- return this.replace(/\\([\\'"])/g, '$1');
- };
- String.prototype.reverse = function() {
- return this.split(/|/).reverse().join('');
- };
- Array.prototype.shuffle = function() {
- var i = 0, l = this.length, r, swap;
- while (i < l) {
- r = Math.floor( Math.random() * l );
- swap = this[r];
- this[r] = this[i];
- this[i++] = swap;
- }
- };
- // [1, 2, 3, 4, 5].rand() -> 4
- Array.prototype.rand = function() {
- return this[Math.floor( Math.random() * this.length )];
- };
- HTMLCanvasElement.prototype.toBlob = function(type, quality) {
- var dataURL = this.toDataURL(type, quality), binary = atob( dataURL.substr( dataURL.indexOf(',') + 1 ) ), i = binary.length, view = new Uint8Array(i);
- while (i--) {
- view[i] = binary.charCodeAt(i);
- }
- return new Blob([view], {type: type});
- };
- ( function() {
- var cache = {};
- gid = function(x) {
- return cache[x] ? cache[x] : cache[x] = document.getElementById(x);
- };
- } )();
- function loadScript(url, cb) {
- var d = document, s = d.createElement('script');
- s.src = url;
- s.onload = cb;
- d.head.appendChild(s);
- }
- function loadScripts(urls, cb) {
- loadScript( urls.shift(), function() {
- if (urls.length) {
- return loadScripts(urls, cb);
- }
- cb && cb();
- } );
- }
- function onHashChange(cb) {
- var cur = location.hash;
- setInterval( function() {
- if (cur != location.hash) {
- cur = location.hash;
- cb();
- }
- }, 100 );
- }
- function extend(dst, src) {
- for (var p in src) {
- if( src.hasOwnProperty(p) ) {
- dst[p] = src[p];
- }
- }
- return dst;
- }
- function clone(o) {
- return JSON.parse( JSON.stringify(o) );
- }
- function rand(min, max) {
- return min + Math.floor( Math.random() * (max + 1 - min) );
- }
- function deg2rad(n) {
- return n * (Math.PI / 180);
- }
- function moveAtAngle(sx, sy, angle, distance) {
- return [sx + Math.cos(angle) * distance, sy + Math.sin(angle) * distance]
- }
- function hexToRgb(s) {
- if ( /^#([0-9a-f]{3}|[0-9a-f]{6})$/ig.test(s) ) {
- var hex = s.substr(1), rgb = parseInt( hex.length == 3 ? hex.replace(/(.)/g, '$1$1') : hex, 16 );
- return 'rgb(' + [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255].join(',') + ')';
- }
- return false;
- }
- function rgbToHex(red, green, blue) {
- var out = '#';
- for (var i = 0; i < 3; ++i) {
- var n = typeof arguments[i] == 'number' ? arguments[i] : parseInt(arguments[i]);
- if (isNaN(n) || n < 0 || n > 255) {
- return false;
- }
- out += (n < 16 ? '0' : '') + n.toString(16);
- }
- return out;
- }
- /**
- * Возвращает размер в байтах в понятном для человека формате.
- *
- * @param size размер в байтах, целое число
- * @param standard стандарт, 'si' | 'iec'
- * @return string
- */
- function formatSize(size, standard) {
- var n = 0, base = standard == 'si' ? 1000 : 1024, prefixes = ' KMGTPEZY';
- standard = standard ? standard.toLowerCase() : standard;
- 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, parts = [];
- weeks >= 1 && parts.push( pluralize( Math.floor(weeks), 'недел', 'я', 'и', 'ь' ) );
- days >= 1 && parts.push( pluralize( Math.floor(days), 'д', 'ень', 'ня', 'ней' ) );
- hours >= 1 && parts.push( pluralize( Math.floor(hours), 'час', '', 'а', 'ов' ) );
- minutes >= 1 && parts.push( pluralize( Math.floor(minutes), 'минут', 'а', 'ы', '' ) );
- seconds >= 0.5 && parts.push( pluralize( Math.round(seconds), 'секунд', 'а', 'ы', '') );
- return parts.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);
- }
- ( function() {
- var s = '^!"#$%&\'()*+,./:;<=>?@\\[\\\\\\]^_`{|}~',
- s1 = '[' + s + '-]+(?:[' + s + ']+[' + s + '-])*',
- re = new RegExp( '^' + [
- // протокол
- '(?:([^:@/?#]*:)\\/\\/)?',
- // пользователь и пароль
- '(?:([^:@/?#]*)(?::([^:@/?#]*))?@)?',
- // хост и порт
- '((' + s1 + '(?:\\.' + s1 + ')*)(?::(\\d+))?)?',
- // путь
- '(/[^?#]*)?',
- // часть после вопроса
- '(\\?[^#]*)?',
- // хеш
- '(#.*)?'
- ].join('') + '$' );
- // console.log(re);
- parseURL = function(s) {
- // проверяем на наличие символов с ascii кодами меньше 33, а так же на правильность кодирования
- if ( /^(?:[^\x00-\x20%]|%[a-zA-Z0-9]{2})*$/.test(s) ) {
- var parts = re.exec(s);
- if (parts !== null) {
- var scheme = ['protocol', 'user', 'password', 'hostname', 'host', 'port', 'pathname', 'search', 'hash'], i = 0, l = scheme.length, o = {};
- while (i < l) {
- o[scheme[i]] = parts[++i] === undefined ? '' : parts[i];
- }
- if (o.pathname) {
- o.pathname = o.pathname.replace(/\\/g, '/').replace(/\/{2,}/g, '/');
- }
- return o;
- }
- }
- return false;
- };
- } )();
- querystring = {
- parse: function(s, sep, eq) {
- var o = {};
- eq = eq || '=';
- if (s) {
- var a = s.split(sep || '&'), i = 0, l = a.length, a1, k, v;
- while (i < l) {
- a1 = a[i++].split(eq);
- k = a1[0];
- v = a1[1];
- if (k !== '') {
- k = decodeURIComponent(k);
- v = v === undefined ? '' : decodeURIComponent(v);
- if (k in o) {
- if (typeof o[k] == 'string') {
- o[k] = new Array(o[k]);
- }
- o[k].push(v);
- }
- else {
- o[k] = v;
- }
- }
- }
- }
- return o;
- },
- stringify: function(o, sep, eq) {
- var p, i, l, a, a1 = [];
- sep = sep || '&';
- eq = eq || '=';
- for (p in o) {
- if ( o.hasOwnProperty(p) ) {
- a = Array.prototype.concat(o[p]);
- p = encodeURIComponent(p);
- for (i = 0, l = a.length; i < l; ++i) {
- a1.push( p + ( a[i] === '' ? '' : eq + encodeURIComponent(a[i]) ) );
- }
- }
- }
- return a1.join(sep);
- }
- };
- // query = querystring.parse( location.search.substr(1) );
- // cookie = querystring.parse(document.cookie, /;\s*/);
- /**
- * Ajax-обертка
- */
- ajax = new ( function(){
- var parseResponse = this.parseResponse = function(xhr, type) {
- if (type) {
- switch ( type.toLowerCase() ) {
- case 'document':
- case 'xml':
- return xhr.responseXML;
- case 'json':
- return JSON.parse(xhr.responseText);
- case 'script':
- return eval(xhr.responseText);
- }
- }
- return xhr.responseText;
- }
- var request = this.request = function(method, url, data, opts) {
- var xhr = new XMLHttpRequest, response, error;
- opts = opts || {};
- if (opts.done || opts.fail || opts.complete) {
- xhr.onreadystatechange = function() {
- if (xhr.readyState == 4) {
- if (xhr.status >= 200 && xhr.status < 300) {
- response = parseResponse(xhr, opts.responseType);
- if (opts.done) {
- return opts.done(response, xhr);
- }
- }
- else {
- error = xhr.responseText;
- if (opts.fail) {
- return opts.fail(error, xhr);
- }
- }
- opts.complete(error, response, xhr);
- }
- }
- }
- xhr.open(method, url);
- if (opts.contentType) {
- xhr.setRequestHeader('Content-Type', opts.contentType);
- }
- xhr.send(data);
- };
- this.get = function(url, opts) {
- request('GET', url, null, opts);
- };
- this.rawpost = function(url, data, opts) {
- request('POST', url, data, opts);
- };
- this.put = function(url, data, opts) {
- request('PUT', url, data, opts);
- };
- /**
- * Отправить данные методом POST
- *
- * @param url адрес документа
- * @param data ассоциативный массив
- * @param opts.contentType тип передаваемых данных
- * @param opts.responseType тип получаемых данных: 'xml', 'json', 'script'
- * @param opts.done function(data, xhr) { ... } функция-обработчик, которая вызывается при успешном выполнении запроса
- * @param opts.fail function(err, xhr) { ... } функция-обработчик, которая вызывается при возвращении сервером статуса отличного от 2XX
- * @param opts.complete function(err, data, xhr) { ... } объединяет в себе done и fail
- */
- this.post = function(url, data, opts) {
- opts = opts || {};
- opts.contentType = opts.contentType || 'application/x-www-form-urlencoded';
- this.rawpost( url, querystring.stringify(data), opts );
- };
- } )();
- ( function() {
- var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
- base62 = {
- encode: function(n) {
- var s = '';
- do {
- s = chars[n % 62] + s;
- }
- while ( n = Math.floor(n / 62) );
- return s;
- },
- decode: function(s) {
- var q = s.length, w, e = 0, r = 0;
- while (q--) {
- if ( ( w = chars.indexOf(s[q]) ) == -1 ) {
- return false;
- }
- if (w) {
- r += w * Math.pow(62, e);
- }
- ++e;
- }
- return r;
- }
- }
- } )();
Advertisement
Add Comment
Please, Sign In to add comment