Advertisement
stuppid_bot

common.js

Sep 7th, 2014
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // o.hasOwnProperty можно переопределить
  2. function hasOwn(o, p) {
  3.     return Object.prototype.hasOwnProperty.call(o, p);
  4. }
  5.  
  6. // each(obj, function (value, index, obj) {}[, thisArg=obj])
  7. function each(o, cb, s) {
  8.     var i, r;
  9.     s = s || o;
  10.     if (typeof o.length != 'undefined') {
  11.         for (i = 0; i < o.length; ++i) {
  12.             if (cb.call(s, o[i], i, o) === false) {
  13.                 break;
  14.             }
  15.         }
  16.     } else {
  17.         for (i in o) {
  18.             if (hasOwn(o, i)) {
  19.                 if (cb.call(s, o[i], i, o) === false) {
  20.                     break;
  21.                 }
  22.             }
  23.         }
  24.     }
  25.     return o;
  26. }
  27.  
  28. function clone(o) {
  29.     // undefined, null и примитивы
  30.     if (o == null || typeof o != 'object') {
  31.         return o;
  32.     }
  33.     var c = new o.constructor();
  34.     for (var p in o) {
  35.         if (hasOwn(o, p)) {
  36.             c[p] = clone(o[p]);
  37.         }
  38.     }
  39.     return c;
  40. }
  41.  
  42. function extend() {
  43.     var target = arguments[0], i = 1, options, name;
  44.     for (; i < arguments.length; ++i) {
  45.         options = arguments[i];
  46.         for (name in options) {
  47.             if (hasOwn(options, name)) {
  48.                 // clone???
  49.                 target[name] = options[name];
  50.             }
  51.         }
  52.     }
  53.     return target;
  54. }
  55.  
  56. function typeName(o) {
  57.     return Object.prototype.toString.call(o).slice(8, -1);
  58. }
  59.  
  60. function is(t, o) {
  61.     return t == typeName(o);
  62. }
  63.  
  64. function isEmpty(o) {
  65.     // null, undefined
  66.     if (o == null) {
  67.         return true;
  68.     }
  69.     // arrays
  70.     if (o.length > 0) {
  71.         return false;
  72.     }
  73.     if (o.length === 0) {
  74.         return true;
  75.     }
  76.     for (var i in o) {
  77.         if (hasOwn(o, i)) {
  78.             return false;
  79.         }
  80.     }
  81.     return true;
  82. }
  83.  
  84. function isObject(o) {
  85.     return is('Object', o);
  86. }
  87.  
  88. // NOTE: undefined, NaN, Infinity можно переопределить
  89. // typeof 'foo' == 'string', but typeof String('foo') == 'object'
  90. // Примитивы, которые получают тип 'object' при создании через конструктор
  91. function isNumber(o) {
  92.     return is('Number', o);
  93. }
  94.  
  95. function isString(o) {
  96.     return is('String', o);
  97. }
  98.  
  99. function isBoolean(o) {
  100.     return is('Boolean', o);
  101. }
  102.  
  103. function isFunction(o) {
  104.     return is('Function', o);
  105. }
  106.  
  107. // встроенная функция всяко быстрее
  108. function isArray(o) {
  109.     return Array.isArray(o);
  110. }
  111.  
  112. function isElement(o) {
  113.     return o instanceof HTMLElement;
  114. }
  115.  
  116. function isObjectOrArray(o) {
  117.     return isObject(o) || isArray(o);
  118. }
  119.  
  120. function assert(condition, message) {
  121.     if (!condition) {
  122.         throw message || 'Assertion Failed';
  123.     }
  124. }
  125.  
  126. function log(s) {
  127.     console.log.apply(console, arguments);
  128. }
  129.  
  130. function buildQuery(params) {
  131.     if (!isObjectOrArray(params)) {
  132.         throw new TypeError('must be an object or an array');
  133.     }
  134.     return build(params);
  135.     function build(data, prefix, undef) {
  136.         var r = []
  137.             , k
  138.             , v;
  139.         for (var k in data) {
  140.             if (hasOwn(data, k)) {
  141.                 v = data[k];
  142.                 k = encodeURIComponent(k);
  143.                 k = prefix === undef ? k : prefix + '[' + k + ']';
  144.                 r.push(isObjectOrArray(v) ? build(v, k) : k + '=' + encodeURIComponent(v))
  145.             }
  146.         }
  147.         return r.join('&');
  148.     }
  149. }
  150.  
  151. // i18n
  152. function __(s) {
  153.     if (typeof i18n == 'undefined' || !(s in i18n)) {
  154.         log('FIXME: i18n not found for string: ' + s);
  155.     } else {
  156.         s = i18n[s];
  157.     }
  158.     return s;
  159. }
  160.  
  161. // dom
  162. function $(sel, start) {
  163.     return (start || document).querySelector(sel);
  164. }
  165.  
  166. function $$(sel, start) {
  167.     return (start || document).querySelectorAll(sel);
  168. }
  169.  
  170. function ge(el) {
  171.     return isElement(el) ? el : document.getElementById(el);
  172. }
  173.  
  174. function val(el, v) {
  175.     el = ge(el);
  176.     var i = /^(INPUT|TEXTAREA)$/.test(el.tagName) ? 'value': 'innerHTML';
  177.     return arguments.length > 1 ? el[i] = v : el[i];
  178. }
  179.  
  180. function ce(tag, attr, children) {
  181.     var el = document.createElement(tag);
  182.     if (attr) {
  183.         extend(el, attr);
  184.     }
  185.     if (children) {
  186.         if (isArray(children)) {
  187.             for (var i = 0; i < children.length; ++i) {
  188.                 el.appendChild(children[i]);
  189.             }
  190.         } else {
  191.             el.appendChild(children);
  192.         }
  193.     }
  194.     return el;
  195. }
  196.  
  197. function addScript(u) {
  198.     var s = ce('script', {type: 'text/javascript', src: u});
  199.     document.head.appendChild(s);
  200. }
  201.  
  202. // <div id="mydiv" data-toggle="className" />
  203. function toggle(el) {
  204.     el = ge(el);
  205.     var cls = el.getAttribute('data-toggle');
  206.     if (cls === null) {
  207.         return null;
  208.     }
  209.     return el.classList.roggle(cls);
  210. }
  211.  
  212. // random
  213. function rand(min, max) {
  214.     return Math.floor(Math.random() * (max - min + 1) + min);
  215. }
  216.  
  217. function randElement(a) {
  218.     return a[Math.floor(Math.random() * a.length)];
  219. }
  220.  
  221. function randStr(len, chars) {
  222.     var ret = '';
  223.     chars = chars || '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
  224.     while (ret.length < len) {
  225.         ret += chars.charAt(Math.random() * chars.length);
  226.     }
  227.     return ret;
  228. }
  229.  
  230. // array
  231. function shuffle(a) {
  232.     return a.sort(function () {
  233.         return Math.random() > .5;
  234.     });
  235. }
  236.  
  237. function subArray(o, begin, end) {
  238.     return Array.prototype.slice.call(o, begin, end);
  239. }
  240.  
  241. // string
  242. function trim(s) {
  243.     return typeof s.trim != 'undefined' ? s.trim() : s.replace(/^\s+|\s+$/g, '');
  244. }
  245.  
  246. function ltrim(s) {
  247.     return typeof s.ltrim != 'undefined' ? s.ltrim() : s.replace(/^\s+/, '');
  248. }
  249.  
  250. function rtrim(s) {
  251.     return typeof s.rtrim != 'undefined' ? s.rtrim() : s.replace(/\s+$/, '');
  252. }
  253.  
  254. function wrap(s, w, br) {
  255.     w = w || 80;
  256.     if (s.length <= w) {
  257.         return s;
  258.     }
  259.     br = br || '\n';
  260.     var re = new RegExp('(.{1,' + w + '})[\\t\\r ]+|(.{1,' + w + '})', 'g'); // => /(.{1,80})[\t\r ]+|(.{1,80})/g
  261.     s = s.split('\n');
  262.     for (var i = 0; i < s.length; ++i) {
  263.         if (s[i].length > w) {
  264.             s[i] = s[i].match(re).map(function (v) { return rtrim(v); }).join(br);
  265.         }
  266.     }
  267.     return s.join('\n');
  268. }
  269.  
  270. function startsWith(haystack, needle) {
  271.     return needle == haystack.substr(0, needle.length);
  272. }
  273.  
  274. function endsWith(haystack, needle) {
  275.     return needle == haystack.substr(-needle.length);
  276. }
  277.  
  278. function containsStr(haystack, needle) {
  279.     return haystack.indexOf(needle) >= 0;
  280. }
  281.  
  282. function ucfirst(s) {
  283.     return s.charAt(0).toUpperCase() + s.substr(1);
  284. }
  285.  
  286. function capitalize(s) {
  287.     return s.replace(/\b[a-z]/g, function (c) {
  288.         return c.toUpperCase();
  289.     });
  290. }
  291.  
  292. function reverseStr(s) {
  293.     return s.split('').reverse().join('');
  294. }
  295.  
  296. function repeatStr(s, n) {
  297.     return Array(++n).join(s);
  298. }
  299.  
  300. function lpad(s, l, c) {
  301.     if (s.length >= l) return s;
  302.     c = c || ' ';
  303.     while (s.length < l) {
  304.         s = c + s;
  305.     }
  306.     return s.length > l ? s.substr(0, l) : s;
  307. }
  308.  
  309. function rpad(s, l, c) {
  310.     if (s.length >= l) return s;
  311.     c = c || ' ';
  312.     while (s.length < l) {
  313.         s += c;
  314.     }
  315.     return s.length > l ? s.substr(0, l) : s;
  316. }
  317.  
  318. function center(s, l, c) {
  319.     if (s.length >= l) return s;
  320.     c = c || ' ';
  321.     l = (l - s.length) / 2;
  322.     var repeater = repeatStr(c, Math.ceil(l / c.length));
  323.     return repeater.substr(0, Math.floor(l)) + s + repeater.substr(0, Math.ceil(l))
  324. }
  325.  
  326. function escapeRe(s) {
  327.     return s.replace(/([-.\\+*?[^\]$(){}=!<>|:])/g, '\\$1');
  328. }
  329.    
  330. function addSlashes(s) {
  331.     return s.replace(/([\\'"])/g, '\\$1');
  332. }
  333.  
  334. function stripSlashes(s) {
  335.     return s.replace(/\\([\\'"])/g, '$1');
  336. }
  337.  
  338. function encodeHtml(s) {
  339.     return s.replace(/[<>&"']/g, function (c) {
  340.         return  {
  341.             '<': '&lt;',
  342.             '>': '&gt;',
  343.             '&': '&amp;',
  344.             '"': '&quot;',
  345.             "'": '&#39;'
  346.         }[c];
  347.     });
  348. }
  349.  
  350. function decodeHtml(s) {
  351.     var el = document.createElement('div');
  352.     s = s.replace('<', '&lt;');
  353.     s = s.replace('>', '&gt;');
  354.     el.innerHTML = s;
  355.     return el.textContent;
  356. }
  357.  
  358. function encodeEntities(s) {
  359.     var r = '';
  360.     for (var i = 0; i < s.length; ++i) {
  361.         r += '&#' + s.charCodeAt(i) + ';';
  362.     }
  363.     return r;
  364. }
  365.  
  366. function stripTags(s) {
  367.     return s.replace(/<[\s\S]+?>/g, '');
  368. }
  369.  
  370. function template(str, data) {
  371.     return str.replace(/\{(.*?)\}/g, function (match, name) {
  372.         var keys = name.split('.'), key, node = data;
  373.         for (var i = 0; i < keys.length; ++i) {
  374.             key = keys[i];
  375.             node = node[key];
  376.         }
  377.         return node;
  378.     });
  379. }
  380.  
  381. function format(s) {
  382.     var arg = Array.prototype.slice.call(arguments, 1);
  383.     return s.replace(/\{(\d+)\}/g, function (match, index) {
  384.         if (index >= arg.length) {
  385.             throw new Error('Index out of range');
  386.         }
  387.         return arg[index];
  388.     });
  389. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement