Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function gi(id) {
- return document.getElementById(id);
- }
- function $(selector, element) {
- element = element || document;
- return element.querySelector(selector);
- }
- function $$(selector, element) {
- element = element || document;
- return element.querySelectorAll(selector);
- }
- function clone(o) {
- if (o == null || typeof o != 'object') {
- return o;
- }
- var copy = o.constructor();
- for (var i in o) {
- copy[i] = clone(o[i]);
- }
- return copy;
- }
- function isElement(o) {
- return o instanceof HTMLElement;
- }
- function isArray(o) {
- return o instanceof Array;
- }
- function isObject(o) {
- return o && o.constructor == Object;
- }
- function val(element, value) {
- element = isElement(element) ? element : gi(element);
- var prop = element.tagName == 'INPUT' || element.tagName == 'TEXTAREA' ? 'value' : 'innerHTML';
- return arguments.length > 1 ? element[prop] = value : element[prop];
- }
- function rand(min, max) {
- return Math.floor(Math.random() * (max - min + 1) + min);
- }
- // function shuffle(arr) {
- // return arr.sort(function () {
- // return Math.random() - .5;
- // });
- // }
- function shuffle(a) {
- for (var i = 0, j, k; i < a.length; ++i) {
- j = Math.floor(Math.random() * a.length);
- k = a[j];
- a[j] = a[i];
- a[i] = k;
- }
- // return a;
- }
- function choice(arr) {
- return arr[Math.floor(Math.random() * arr.length)];
- }
- function randStr(length, chars){
- length = length || 6;
- chars = chars || 'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890';
- var ret = '';
- while (length--) {
- ret += chars.charAt(Math.random() * chars.length);
- }
- return ret;
- }
- /**
- * Заменяет на HTML-сущности спецсимволы: \&\, \<\, \>\, \"\.
- * @param {string} string
- * @return {string}
- */
- function escapeHTML(str) {
- return str.replace(/[&"<>]/g, function (x) {
- return '&' + {'&': 'amp', '"': 'quot', '<': 'lt', '>': 'gt'}[x] + ';';
- });
- }
- /**
- * Экранирует символы: /\/, /'/, /"/.
- * @param {string} str
- * @return {string}
- */
- function addSlashes(str) {
- return str.replace(/([\\'"])/g, '\\$1');
- }
- /**
- * Обратная функция для addSlashes.
- * @param {string} str
- * @return {string}
- */
- function stripSlashes(str) {
- return str.replace(/\\([\\'"])/g, '$1');
- }
- /**
- * Экранирует специальные символы, используемые в регулярном выражении.
- * @param {string} str
- * @return {string}
- */
- function escapePattern(str) {
- return str.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
- }
- /**
- * «Переворачивает» строку.
- * @param {string} str
- * @return {string}
- **/
- function reverseStr(str) {
- return str.split(/|/).reverse().join('');
- }
- function repeatStr(str, n) {
- return new Array(++n).join(str);
- }
- function pad(s, len, padder, direction) {
- // len = len || 78;
- if (s.length < len) {
- len = len - s.length;
- padder = typeof padder == 'number' || padder ? padder + '' : ' ';
- direction = direction ? direction.toLowerCase() : 'left';
- if (direction == 'both') {
- return pad('', Math.floor(len / 2), padder) + s + pad('', Math.ceil(len / 2), padder, 'right');
- }
- padder = repeatStr(padder, Math.ceil(len / padder.length)).substr(0, len);
- s = direction == 'right' ? s + padder : padder + s;
- }
- return s;
- }
- function rpad(s, len, padder) {
- return pad(s, len, padder, 'right');
- }
- function center(s, len, padder) {
- return pad(s, len, padder, 'both');
- }
- function wrap(text, width, br) {
- var lines, i, re, line, buf, matches, whitespace, word;
- width = arguments.length > 1 ? arguments[1] : 78;
- br = arguments.length > 2 ? arguments[2] : '\n';
- lines = text.split('\n');
- for (i = 0; i < lines.length; ++i) {
- re = /(\s*)(\S+)/g;
- line = [];
- buf = '';
- while (matches = re.exec(lines[i])) {
- console.log(matches);
- whitespace = matches[1];
- word = matches[2];
- if (buf.length + whitespace.length + word.length <= width) {
- buf += whitespace;
- }
- else if (buf.length) {
- line.push(buf);
- buf = '';
- }
- buf += word;
- }
- line.push(buf);
- lines[i] = line.join(br);
- }
- return lines.join('\n');
- }
- function canvasToBlob(canvas, type, quality) {
- var data = canvas.toDataURL(type, quality);
- data = atob(data.substr(data.indexOf(',') + 1));
- var i = data.length;
- var arr = new Uint8Array(i);
- while (i--) {
- arr[i] = data.charCodeAt(i);
- }
- return new Blob([arr], {type: type});
- }
- /*
- * @example
- * // 0 - Jan
- * alert('Age: ' + getAge(new Date(1988, 3, 20)));
- * @param {Date} birthday
- * @return {number} age
- **/
- function getAge(birthday) {
- var now = new Date();
- var age = now.getYear() - birthday.getYear();
- if (now.getMonth() < birthday.getMonth() ||
- (now.getMonth() == birthday.getMonth() &&
- now.getDate() < birthday.getDate())) {
- --age;
- }
- return age;
- }
- /**
- * Сохраняет файл по ссылке под определенным именем.
- * @param {string} url Путь до файла на сервере либо Data URI.
- * @param {string} name Имя сохраняемого файла.
- */
- function saveFile(url, name) {
- name = name || 'file';
- var link = document.createElement('a');
- link.setAttribute('download', name);
- link.href = url;
- link.onclick = function () {
- document.body.removeChild(this);
- };
- link.style.display = 'none';
- document.body.appendChild(link);
- link.click();
- }
- function formatSize(size) {
- // if (typeof(size) != 'number' and size >= 0) {
- // throw new TypeError('size must be unsigned number');
- // }
- var base = 1024;
- var prefixes = 'KMGTPEZY';
- var n = 0;
- if (size < 1) {
- return size;
- }
- else if (size >= base) {
- n = Math.floor(Math.log(size) / Math.log(base));
- if (n > prefixes.length) {
- throw new Error('size to big');
- }
- size = (size / Math.pow(base, n)).toFixed(2) * 1;
- }
- return size + ' ' + (n ? prefixes[n] : '') + 'B';
- }
- var ajax = new Function();
- ajax.getReq = function (m, u, cb) {
- var r = new XMLHttpRequest();
- r.open(m,u);
- r.onload = function () {
- typeof cb == 'function' && cb(r);
- };
- r.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
- return r;
- };
- ajax.get = function (u, cb) {
- var r = this.getReq('GET', u, cb);
- r.send();
- };
- ajax.load = function (u, e) {
- this.get(u, function (r) {
- val(e, r.response);
- });
- };
- ajax.post = function(u, p, cb) {
- var r = this.getReq('POST', u, cb), q = '', k;
- r.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
- for (k in p) {
- if (p.hasOwnProperty(k)) {
- q += (q.length ? '&': '') + k + '=' + encodeURIComponent(p[k]);
- };
- }
- r.send(q);
- };
- ajax.submit = function (e, cb) {
- e = ge(e);
- var r = this.getReq('POST', e.action, cb), fd = new FormData(e);
- r.send(fd);
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement