Advertisement
stuppid_bot

Функции

Sep 7th, 2014
256
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.             r = cb.call(s, o[i], i, o);
  13.             if (r == false) {
  14.                 break;
  15.             }
  16.         }
  17.     } else {
  18.         for (i in o) {
  19.             if (hasOwn(o, i)) {
  20.                 r = cb.call(s, o[i], i, o);
  21.                 if (r == false) {
  22.                     break;
  23.                 }
  24.             }
  25.         }
  26.     }
  27.     return o;
  28. }
  29.  
  30. function clone(o) {
  31.     // undefined, null и примитивы
  32.     if (o == null || typeof o != 'object') {
  33.         return o;
  34.     }
  35.     var c = new o.constructor();
  36.     for (var p in o) {
  37.         if (hasOwn(o, p)) {
  38.             c[p] = clone(o[p]);
  39.         }
  40.     }
  41.     return c;
  42. }
  43.  
  44. function extend(a, b) {
  45.     for (var i in b) {
  46.         if (hasOwn(b, i)) {
  47.             a[i] = b[i];
  48.         }
  49.     }
  50.     return a;
  51. }
  52.  
  53. function typeName(o) {
  54.     return Object.prototype.toString.call(o).slice(8, -1);
  55. }
  56.  
  57. function is(t, o) {
  58.     return t == typeName(o);
  59. }
  60.  
  61. function isObject(o) {
  62.     return is('Object', o);
  63. }
  64.  
  65. // NOTE: undefined, NaN, Infinity можно переопределить
  66. // typeof 'foo' == 'string', but typeof String('foo') == 'object'
  67. // Примитивы, которые получают тип 'object' при создании через конструктор
  68. function isNumber(o) {
  69.     return is('Number', o);
  70. }
  71.  
  72. function isString(o) {
  73.     return is('String', o);
  74. }
  75.  
  76. function isBoolean(o) {
  77.     return is('Boolean', o);
  78. }
  79.  
  80. // встроенная функция всяко быстрее
  81. function isArray(o) {
  82.     return Array.isArray(o);
  83. }
  84.  
  85. function isElement(o) {
  86.     return o instanceof HTMLElement;
  87. }
  88.  
  89. function isObjectOrArray(o) {
  90.     return isObject(o) || isArray(o);
  91. }
  92.  
  93. function assert(condition, message) {
  94.     if (!condition) {
  95.         throw message || 'Assertion Failed';
  96.     }
  97. }
  98.  
  99. function log(s) {
  100.     console.log.apply(console, arguments);
  101. }
  102.  
  103. function __(s) {
  104.     if (typeof i18n == 'undefined' || !(s in i18n)) {
  105.         log('FIXME: i18n not found for string: ' + s);
  106.     } else {
  107.         s = i18n[s];
  108.     }
  109.     return s;
  110. }
  111.  
  112. function $(sel, start) {
  113.     return (start || document).querySelector(sel);
  114. }
  115.  
  116. function $$(sel, start) {
  117.     return (start || document).querySelectorAll(sel);
  118. }
  119.  
  120. function ge(el) {
  121.     return isElement(el) ? el : document.getElementById(el);
  122. }
  123.  
  124. function val(el, v) {
  125.     el = ge(el);
  126.     var i = /^(INPUT|TEXTAREA)$/.test(el.tagName) ? 'value': 'innerHTML';
  127.     return arguments.length > 1 ? el[i] = v : el[i];
  128. }
  129.  
  130. function ce(tag, attr, children) {
  131.     var el = document.createElement(tag);
  132.     if (attr) {
  133.         extend(el, attr);
  134.     }
  135.     if (children) {
  136.         if (isArray(children)) {
  137.             for (var i = 0; i < children.length; ++i) {
  138.                 el.appendChild(children[i]);
  139.             }
  140.         } else {
  141.             el.appendChild(children);
  142.         }
  143.     }
  144.     return el;
  145. }
  146.  
  147. // random
  148. function rand(min, max) {
  149.     return Math.floor(Math.random() * (max - min + 1) + min);
  150. }
  151.  
  152. function randElement(a) {
  153.     return a[Math.floor(Math.random() * a.length)];
  154. }
  155.  
  156. function randStr(len, chars) {
  157.     var ret = '';
  158.     chars = chars || '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
  159.     while (ret.length < len) {
  160.         ret += chars.charAt(Math.random() * chars.length);
  161.     }
  162.     return ret;
  163. }
  164.  
  165. // array
  166. function shuffle(a) {
  167.     return a.sort(function () {
  168.         return Math.random() > .5;
  169.     });
  170. }
  171.  
  172. function subArray(o, begin, end) {
  173.     return Array.prototype.slice.call(o, begin, end);
  174. }
  175.  
  176. // string
  177. function trim(s) {
  178.     return typeof s.trim != 'undefined' ? s.trim() : s.replace(/^\s+|\s+$/g, '');
  179. }
  180.  
  181. function ltrim(s) {
  182.     return typeof s.ltrim != 'undefined' ? s.ltrim() : s.replace(/^\s+/, '');
  183. }
  184.  
  185. function rtrim(s) {
  186.     return typeof s.rtrim != 'undefined' ? s.rtrim() : s.replace(/\s+$/, '');
  187. }
  188.  
  189. function wrap(s, w, br) {
  190.     w = w || 80;
  191.     if (s.length <= w) {
  192.         return s;
  193.     }
  194.     br = br || '\n';
  195.     var re = new RegExp('(.{1,' + w + '})[\\t\\r ]+|(.{1,' + w + '})', 'g'); // => /(.{1,80})[\t\r ]+|(.{1,80})/g
  196.     s = s.split('\n');
  197.     for (var i = 0; i < s.length; ++i) {
  198.         if (s[i].length > w) {
  199.             s[i] = s[i].match(re).map(function (v) { return rtrim(v); }).join(br);
  200.         }
  201.     }
  202.     return s.join('\n');
  203. }
  204.  
  205. function startsWith(haystack, needle) {
  206.     return needle == haystack.substr(0, needle.length);
  207. }
  208.  
  209. function endsWith(haystack, needle) {
  210.     return needle == haystack.substr(-needle.length);
  211. }
  212.  
  213. function containsStr(haystack, needle) {
  214.     return haystack.indexOf(needle) >= 0;
  215. }
  216.  
  217. function ucfirst(s) {
  218.     return s.charAt(0).toUpperCase() + s.substr(1);
  219. }
  220.  
  221. function capitalize(s) {
  222.     return s.replace(/\b[a-z]/g, function (c) {
  223.         return c.toUpperCase();
  224.     });
  225. }
  226.  
  227. function reverseStr(s) {
  228.     return s.split('').reverse().join('');
  229. }
  230.  
  231. function repeatStr(s, n) {
  232.     return Array(++n).join(s);
  233. }
  234.  
  235. function lpad(s, l, c) {
  236.     if (s.length >= l) return s;
  237.     c = c || ' ';
  238.     while (s.length < l) {
  239.         s = c + s;
  240.     }
  241.     return s.length > l ? s.substr(0, l) : s;
  242. }
  243.  
  244. function rpad(s, l, c) {
  245.     if (s.length >= l) return s;
  246.     c = c || ' ';
  247.     while (s.length < l) {
  248.         s += c;
  249.     }
  250.     return s.length > l ? s.substr(0, l) : s;
  251. }
  252.  
  253. function center(s, l, c) {
  254.     if (s.length >= l) return s;
  255.     c = c || ' ';
  256.     l = (l - s.length) / 2;
  257.     var repeater = repeatStr(c, Math.ceil(l / c.length));
  258.     return repeater.substr(0, Math.floor(l)) + s + repeater.substr(0, Math.ceil(l))
  259. }
  260.  
  261. function escapeRe(s) {
  262.     return s.replace(/([-.\\+*?[^\]$(){}=!<>|:])/g, '\\$1');
  263. }
  264.    
  265. function addSlashes(s) {
  266.     return s.replace(/([\\'"])/g, '\\$1');
  267. }
  268.  
  269. function stripSlashes(s) {
  270.     return s.replace(/\\([\\'"])/g, '$1');
  271. }
  272.  
  273. function encodeHtml(s) {
  274.     return s.replace(/[<>&"']/g, function (c) {
  275.         return  {
  276.             '<': '&lt;',
  277.             '>': '&gt;',
  278.             '&': '&amp;',
  279.             '"': '&quot;',
  280.             "'": '&#39;'
  281.         }[c];
  282.     });
  283. }
  284.  
  285. function decodeHtml(s) {
  286.     var el = document.createElement('div');
  287.     s = s.replace('<', '&lt;');
  288.     s = s.replace('>', '&gt;');
  289.     el.innerHTML = s;
  290.     return el.textContent;
  291. }
  292.  
  293. function encodeEntities(s) {
  294.     var r = '';
  295.     for (var i = 0; i < s.length; ++i) {
  296.         r += '&#' + s.charCodeAt(i) + ';';
  297.     }
  298.     return r;
  299. }
  300.  
  301. function stripTags(s) {
  302.     return s.replace(/<[\s\S]+?>/g, '');
  303. }
  304.  
  305. function template(str, data) {
  306.     return str.replace(/\{(.*?)\}/g, function (match, name) {
  307.         var keys = name.split('.'), key, node = data;
  308.         for (var i = 0; i < keys.length; ++i) {
  309.             key = keys[i];
  310.             node = node[key];
  311.         }
  312.         return node;
  313.     });
  314. }
  315.  
  316. function format(s) {
  317.     var arg = Array.prototype.slice.call(arguments, 1);
  318.     return s.replace(/\{(\d+)\}/g, function (match, index) {
  319.         if (index >= arg.length) {
  320.             throw new Error('Index out of range');
  321.         }
  322.         return arg[index];
  323.     });
  324. }
  325.  
  326. (function (win) {
  327.     'use strict';
  328.     var encodeMap = {
  329.         '\0': '0',
  330.         '\b': 'b',
  331.         '\t': 't',
  332.         '\n': 'n',
  333.         '\v': 'v',
  334.         '\f': 'f',
  335.         '\r': 'r',
  336.         '"': '"',
  337.         "'": "'",
  338.         '\\': '\\'
  339.     };
  340.     var decodeMap = {};
  341.     for (var p in encodeMap) {
  342.         decodeMap[encodeMap[p]] = p;
  343.     }
  344.  
  345.     win.encodeUnicode = function (s) {
  346.         var re = /[^\x20\x21\x23-\x26\x28-\x5b\x5d-\x7e]/g;
  347.         return s.replace(re, function (chr) {
  348.             var ret;
  349.             if (chr in encodeMap) {
  350.                 ret = '\\' + encodeMap[chr];
  351.             } else {
  352.                 var code = chr.charCodeAt(0);
  353.                 if (code < 128) {
  354.                     ret = '\\x' + (code < 16 ? '0' : '') + code.toString(16);
  355.                 } else {
  356.                     ret = '\\u' + ('000' + code.toString(16)).slice(-4);
  357.                 }
  358.             }
  359.             return ret;
  360.         });
  361.     };
  362.  
  363.     win.decodeUnicode = function (s) {
  364.         var re = /\\((?:[1-7][0-7]{0,2}|[0-7]{2,3}))|\\x([\da-f]{2})|\\u([\da-f]{4})|\\(.)/gi;
  365.         return s.replace(re, function (m, o, h, u, c) {
  366.             if (o) {
  367.                 c = String.fromCharCode(parseInt(o, 8));
  368.             } else if (h) {
  369.                 c = String.fromCharCode(parseInt(h, 16));
  370.             } else if (u) {
  371.                 c = String.fromCharCode(parseInt(u, 16));
  372.             } else if ('xuXU'.indexOf(c) != -1) {
  373.                 throw new Error('bad sequence');
  374.             } else if (c in decodeMap) {
  375.                 c = decodeMap[c];
  376.             }
  377.             return c;
  378.         });
  379.     };
  380. })(window);
  381.  
  382. (function (win) {
  383.     'use strict';
  384.     var intervals = [];
  385.     var _setInterval = setInterval;
  386.     var _clearInterval = clearInterval;
  387.  
  388.     win.setInterval = function () {
  389.         var id = _setInterval.apply(win, arguments);
  390.         intervals.push(id);
  391.         return id;
  392.     };
  393.  
  394.     win.clearInterval = function (id) {
  395.         _clearInterval.call(win, id);
  396.         intervals.splice(intervals.indexOf(id), 1);
  397.     };
  398.  
  399.     win.getIntervals = function () {
  400.         return Array.prototype.slice.call(intervals);
  401.     };
  402.  
  403.     win.clearAllIntervals = function () {
  404.         for (var i = 0; i < intervals.length; ++i) {
  405.             _clearInterval.call(win, intervals[i]);
  406.         }
  407.         intervals = [];
  408.     }
  409. })(window);
  410.  
  411. function bytesToSize(bytes) {
  412.     var base = 1024
  413.         , units = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  414.         , i = parseInt(Math.log(bytes) / Math.log(base));
  415.     return !isNaN(i) && i < units.length ? (bytes / Math.pow(base, i)).toFixed(2) * 1 + ' ' + units[i] : 'n/a';
  416. }
  417.  
  418. function download(url, name) {
  419.     var link = document.createElement('a');
  420.     link.setAttribute('download', name);
  421.     link.href = url;
  422.     link.click();
  423. }
  424.  
  425. // <div id="mydiv" data-toggle="className" />
  426. function toggle(el) {
  427.     el = ge(el);
  428.     var cls = el.getAttribute('data-toggle');
  429.     if (cls === null) return null;
  430.     return el.classList.roggle(cls);
  431. }
  432.  
  433. function hexRgb(h) {
  434.     h = h.match(/^#?([\da-f]{3}|[\da-f]{6})$/i);
  435.     if (!h) return null;
  436.     h = h[1];
  437.     h = parseInt(h.length == 3 ? h.replace(/(.)/g, '$1$1') : h, 16);
  438.     return [h >> 16, h >> 8 & 255, h & 255];
  439. }
  440.  
  441. function rgbHex(r, g, b) {
  442.     var h = (((r & 255) << 16) + ((g & 255) << 8) + (b & 255)).toString(16);
  443.     return '#000000'.slice(0, -h.length) + h;
  444. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement