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) {
- if (cb.call(s, o[i], i, o) === false) {
- break;
- }
- }
- } else {
- for (i in o) {
- if (hasOwn(o, i)) {
- if (cb.call(s, o[i], i, o) === 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() {
- var target = arguments[0], i = 1, options, name;
- for (; i < arguments.length; ++i) {
- options = arguments[i];
- for (name in options) {
- if (hasOwn(options, name)) {
- // clone???
- target[name] = options[name];
- }
- }
- }
- return target;
- }
- function typeName(o) {
- return Object.prototype.toString.call(o).slice(8, -1);
- }
- function is(t, o) {
- return t == typeName(o);
- }
- function isEmpty(o) {
- // null, undefined
- if (o == null) {
- return true;
- }
- // arrays
- if (o.length > 0) {
- return false;
- }
- if (o.length === 0) {
- return true;
- }
- for (var i in o) {
- if (hasOwn(o, i)) {
- return false;
- }
- }
- return true;
- }
- 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 isFunction(o) {
- return is('Function', 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 buildQuery(params) {
- if (!isObjectOrArray(params)) {
- throw new TypeError('must be an object or an array');
- }
- return build(params);
- function build(data, prefix, undef) {
- var r = []
- , k
- , v;
- for (var k in data) {
- if (hasOwn(data, k)) {
- v = data[k];
- k = encodeURIComponent(k);
- k = prefix === undef ? k : prefix + '[' + k + ']';
- r.push(isObjectOrArray(v) ? build(v, k) : k + '=' + encodeURIComponent(v))
- }
- }
- return r.join('&');
- }
- }
- // i18n
- function __(s) {
- if (typeof i18n == 'undefined' || !(s in i18n)) {
- log('FIXME: i18n not found for string: ' + s);
- } else {
- s = i18n[s];
- }
- return s;
- }
- // dom
- 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;
- }
- function addScript(u) {
- var s = ce('script', {type: 'text/javascript', src: u});
- document.head.appendChild(s);
- }
- // <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);
- }
- // 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];
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement