Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // o.hasOwnProperty можно переопределить
- function hasOwn(o, p) {
- return Object.prototype.hasOwnProperty.call(o, p);
- }
- // each(obj, function (value, index, obj) {}[, thisArg=obj])
- function each(o, cb, s) {
- var i, r;
- s = s || o;
- if (typeof o.length != 'undefined') {
- for (i = 0; i < o.length; ++i) {
- r = cb.call(s, o[i], i, o);
- if (r == false) {
- break;
- }
- }
- } else {
- for (i in o) {
- if (hasOwn(o, i)) {
- r = cb.call(s, o[i], i, o);
- if (r == false) {
- break;
- }
- }
- }
- }
- return o;
- }
- function clone(o) {
- // undefined, null и примитивы
- if (o == null || typeof o != 'object') {
- return o;
- }
- var c = new o.constructor();
- for (var p in o) {
- if (hasOwn(o, p)) {
- c[p] = clone(o[p]);
- }
- }
- return c;
- }
- function extend(a, b) {
- for (var i in b) {
- if (hasOwn(b, i)) {
- a[i] = b[i];
- }
- }
- return a;
- }
- function typeName(o) {
- return Object.prototype.toString.call(o).slice(8, -1);
- }
- function is(t, o) {
- return t == typeName(o);
- }
- function isObject(o) {
- return is('Object', o);
- }
- // NOTE: undefined, NaN, Infinity можно переопределить
- // typeof 'foo' == 'string', but typeof String('foo') == 'object'
- // Примитивы, которые получают тип 'object' при создании через конструктор
- function isNumber(o) {
- return is('Number', o);
- }
- function isString(o) {
- return is('String', o);
- }
- function isBoolean(o) {
- return is('Boolean', o);
- }
- // встроенная функция всяко быстрее
- function isArray(o) {
- return Array.isArray(o);
- }
- function isElement(o) {
- return o instanceof HTMLElement;
- }
- function isObjectOrArray(o) {
- return isObject(o) || isArray(o);
- }
- function assert(condition, message) {
- if (!condition) {
- throw message || 'Assertion Failed';
- }
- }
- function log(s) {
- console.log.apply(console, arguments);
- }
- function __(s) {
- if (typeof i18n == 'undefined' || !(s in i18n)) {
- log('FIXME: i18n not found for string: ' + s);
- } else {
- s = i18n[s];
- }
- return s;
- }
- function $(sel, start) {
- return (start || document).querySelector(sel);
- }
- function $$(sel, start) {
- return (start || document).querySelectorAll(sel);
- }
- function ge(el) {
- return isElement(el) ? el : document.getElementById(el);
- }
- function val(el, v) {
- el = ge(el);
- var i = /^(INPUT|TEXTAREA)$/.test(el.tagName) ? 'value': 'innerHTML';
- return arguments.length > 1 ? el[i] = v : el[i];
- }
- function ce(tag, attr, children) {
- var el = document.createElement(tag);
- if (attr) {
- extend(el, attr);
- }
- if (children) {
- if (isArray(children)) {
- for (var i = 0; i < children.length; ++i) {
- el.appendChild(children[i]);
- }
- } else {
- el.appendChild(children);
- }
- }
- return el;
- }
- // random
- function rand(min, max) {
- return Math.floor(Math.random() * (max - min + 1) + min);
- }
- function randElement(a) {
- return a[Math.floor(Math.random() * a.length)];
- }
- function randStr(len, chars) {
- var ret = '';
- chars = chars || '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
- while (ret.length < len) {
- ret += chars.charAt(Math.random() * chars.length);
- }
- return ret;
- }
- // array
- function shuffle(a) {
- return a.sort(function () {
- return Math.random() > .5;
- });
- }
- function subArray(o, begin, end) {
- return Array.prototype.slice.call(o, begin, end);
- }
- // string
- function trim(s) {
- return typeof s.trim != 'undefined' ? s.trim() : s.replace(/^\s+|\s+$/g, '');
- }
- function ltrim(s) {
- return typeof s.ltrim != 'undefined' ? s.ltrim() : s.replace(/^\s+/, '');
- }
- function rtrim(s) {
- return typeof s.rtrim != 'undefined' ? s.rtrim() : s.replace(/\s+$/, '');
- }
- function wrap(s, w, br) {
- w = w || 80;
- if (s.length <= w) {
- return s;
- }
- br = br || '\n';
- var re = new RegExp('(.{1,' + w + '})[\\t\\r ]+|(.{1,' + w + '})', 'g'); // => /(.{1,80})[\t\r ]+|(.{1,80})/g
- s = s.split('\n');
- for (var i = 0; i < s.length; ++i) {
- if (s[i].length > w) {
- s[i] = s[i].match(re).map(function (v) { return rtrim(v); }).join(br);
- }
- }
- return s.join('\n');
- }
- function startsWith(haystack, needle) {
- return needle == haystack.substr(0, needle.length);
- }
- function endsWith(haystack, needle) {
- return needle == haystack.substr(-needle.length);
- }
- function containsStr(haystack, needle) {
- return haystack.indexOf(needle) >= 0;
- }
- function ucfirst(s) {
- return s.charAt(0).toUpperCase() + s.substr(1);
- }
- function capitalize(s) {
- return s.replace(/\b[a-z]/g, function (c) {
- return c.toUpperCase();
- });
- }
- function reverseStr(s) {
- return s.split('').reverse().join('');
- }
- function repeatStr(s, n) {
- return Array(++n).join(s);
- }
- function lpad(s, l, c) {
- if (s.length >= l) return s;
- c = c || ' ';
- while (s.length < l) {
- s = c + s;
- }
- return s.length > l ? s.substr(0, l) : s;
- }
- function rpad(s, l, c) {
- if (s.length >= l) return s;
- c = c || ' ';
- while (s.length < l) {
- s += c;
- }
- return s.length > l ? s.substr(0, l) : s;
- }
- function center(s, l, c) {
- if (s.length >= l) return s;
- c = c || ' ';
- l = (l - s.length) / 2;
- var repeater = repeatStr(c, Math.ceil(l / c.length));
- return repeater.substr(0, Math.floor(l)) + s + repeater.substr(0, Math.ceil(l))
- }
- function escapeRe(s) {
- return s.replace(/([-.\\+*?[^\]$(){}=!<>|:])/g, '\\$1');
- }
- function addSlashes(s) {
- return s.replace(/([\\'"])/g, '\\$1');
- }
- function stripSlashes(s) {
- return s.replace(/\\([\\'"])/g, '$1');
- }
- function encodeHtml(s) {
- return s.replace(/[<>&"']/g, function (c) {
- return {
- '<': '<',
- '>': '>',
- '&': '&',
- '"': '"',
- "'": '''
- }[c];
- });
- }
- function decodeHtml(s) {
- var el = document.createElement('div');
- s = s.replace('<', '<');
- s = s.replace('>', '>');
- el.innerHTML = s;
- return el.textContent;
- }
- function encodeEntities(s) {
- var r = '';
- for (var i = 0; i < s.length; ++i) {
- r += '&#' + s.charCodeAt(i) + ';';
- }
- return r;
- }
- function stripTags(s) {
- return s.replace(/<[\s\S]+?>/g, '');
- }
- function template(str, data) {
- return str.replace(/\{(.*?)\}/g, function (match, name) {
- var keys = name.split('.'), key, node = data;
- for (var i = 0; i < keys.length; ++i) {
- key = keys[i];
- node = node[key];
- }
- return node;
- });
- }
- function format(s) {
- var arg = Array.prototype.slice.call(arguments, 1);
- return s.replace(/\{(\d+)\}/g, function (match, index) {
- if (index >= arg.length) {
- throw new Error('Index out of range');
- }
- return arg[index];
- });
- }
- (function (win) {
- 'use strict';
- var encodeMap = {
- '\0': '0',
- '\b': 'b',
- '\t': 't',
- '\n': 'n',
- '\v': 'v',
- '\f': 'f',
- '\r': 'r',
- '"': '"',
- "'": "'",
- '\\': '\\'
- };
- var decodeMap = {};
- for (var p in encodeMap) {
- decodeMap[encodeMap[p]] = p;
- }
- win.encodeUnicode = function (s) {
- var re = /[^\x20\x21\x23-\x26\x28-\x5b\x5d-\x7e]/g;
- return s.replace(re, function (chr) {
- var ret;
- if (chr in encodeMap) {
- ret = '\\' + encodeMap[chr];
- } else {
- var code = chr.charCodeAt(0);
- if (code < 128) {
- ret = '\\x' + (code < 16 ? '0' : '') + code.toString(16);
- } else {
- ret = '\\u' + ('000' + code.toString(16)).slice(-4);
- }
- }
- return ret;
- });
- };
- win.decodeUnicode = function (s) {
- var re = /\\((?:[1-7][0-7]{0,2}|[0-7]{2,3}))|\\x([\da-f]{2})|\\u([\da-f]{4})|\\(.)/gi;
- return s.replace(re, function (m, o, h, u, c) {
- if (o) {
- c = String.fromCharCode(parseInt(o, 8));
- } else if (h) {
- c = String.fromCharCode(parseInt(h, 16));
- } else if (u) {
- c = String.fromCharCode(parseInt(u, 16));
- } else if ('xuXU'.indexOf(c) != -1) {
- throw new Error('bad sequence');
- } else if (c in decodeMap) {
- c = decodeMap[c];
- }
- return c;
- });
- };
- })(window);
- (function (win) {
- 'use strict';
- var intervals = [];
- var _setInterval = setInterval;
- var _clearInterval = clearInterval;
- win.setInterval = function () {
- var id = _setInterval.apply(win, arguments);
- intervals.push(id);
- return id;
- };
- win.clearInterval = function (id) {
- _clearInterval.call(win, id);
- intervals.splice(intervals.indexOf(id), 1);
- };
- win.getIntervals = function () {
- return Array.prototype.slice.call(intervals);
- };
- win.clearAllIntervals = function () {
- for (var i = 0; i < intervals.length; ++i) {
- _clearInterval.call(win, intervals[i]);
- }
- intervals = [];
- }
- })(window);
- function bytesToSize(bytes) {
- var base = 1024
- , units = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
- , i = parseInt(Math.log(bytes) / Math.log(base));
- return !isNaN(i) && i < units.length ? (bytes / Math.pow(base, i)).toFixed(2) * 1 + ' ' + units[i] : 'n/a';
- }
- function download(url, name) {
- var link = document.createElement('a');
- link.setAttribute('download', name);
- link.href = url;
- link.click();
- }
- // <div id="mydiv" data-toggle="className" />
- function toggle(el) {
- el = ge(el);
- var cls = el.getAttribute('data-toggle');
- if (cls === null) return null;
- return el.classList.roggle(cls);
- }
- function hexRgb(h) {
- h = h.match(/^#?([\da-f]{3}|[\da-f]{6})$/i);
- if (!h) return null;
- h = h[1];
- h = parseInt(h.length == 3 ? h.replace(/(.)/g, '$1$1') : h, 16);
- return [h >> 16, h >> 8 & 255, h & 255];
- }
- function rgbHex(r, g, b) {
- var h = (((r & 255) << 16) + ((g & 255) << 8) + (b & 255)).toString(16);
- return '#000000'.slice(0, -h.length) + h;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement