andybezbozhny

JavaScript.misc

Oct 17th, 2012 (edited)
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Retrieving query string values via jQuery
  2. // 'name' -  your query string name if there is multiple string
  3. function getValue(name) {
  4.     return decodeURI((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]);
  5. }
  6.  
  7. // Device detection
  8. if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
  9.     // Do something
  10. } else {
  11.     // Do something else
  12. }
  13.  
  14. // date validator
  15. function isValidDate(value, userFormat) {
  16.     // Set default format if format is not provided
  17.     userFormat = userFormat || 'mm/dd/yyyy';
  18.     // Find custom delimiter by excluding
  19.     // month, day and year characters
  20.     let delimiter = /[^mdy]/.exec(userFormat)[0];
  21.  
  22.     // Create an array with month, day and year
  23.     // so we know the format order by index
  24.     let theFormat = userFormat.split(delimiter);
  25.  
  26.     // Create array from user date
  27.     let theDate = value.split(delimiter);
  28.  
  29.     function isDate(date, format) {
  30.         let m, d, y, i = 0, len = format.length, f;
  31.         for (i; i < len; i ++) {
  32.             f = format[i];
  33.             if (/m/.test(f)) m = date[i];
  34.             if (/d/.test(f)) d = date[i];
  35.             if (/y/.test(f)) y = date[i];
  36.         }
  37.         return (
  38.             m > 0 && m < 13 &&
  39.             y && y.length === 4 &&
  40.             d > 0 &&
  41.             // Check if it's a valid day of the month
  42.             d <= (new Date(y, m, 0)).getDate()
  43.         );
  44.     }
  45.  
  46.     return isDate(theDate, theFormat);
  47. }
  48.  
  49. // Javascript склонение
  50. // PluralNumber(days, ‘ д’, ‘ень’, ‘ня’, ‘ней’)
  51. function PluralNumber(count, arg0, arg1, arg2, arg3) {
  52.     let result = arg0;
  53.     let last_digit = count % 10;
  54.     let last_two_digits = count % 100;
  55.  
  56.     if (last_digit == 1 && last_two_digits != 11) {
  57.         result += arg1;
  58.     } else if (
  59.         (last_digit == 2 && last_two_digits != 12)
  60.         ||
  61.         (last_digit == 3 && last_two_digits != 13)
  62.         ||
  63.         (last_digit == 4 && last_two_digits != 14)
  64.     ) {
  65.         result += arg2;
  66.     } else {
  67.         result += arg3;
  68.     }
  69.     return result;
  70. }
  71.  
  72. // Get cookie value
  73. const getCookieValue = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
  74.  
  75. getCookieValue('_ga'); // Результат: "GA1.2.1929736587.1601974046"
  76.  
  77. // Clear all cookies
  78. const clearCookies = document.cookie.split(';').forEach(
  79.     cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`)
  80. );
  81.  
  82. function setCookie(name, value, expires, path, domain, secure) {
  83.     let c = [name + '=' + escape(value)];
  84.  
  85.     if (expires) {
  86.         expires = expires * 1000 * 60 * 60 * 24;
  87.  
  88.         let today = new Date();
  89.         today.setTime(today.getTime());
  90.  
  91.         let expires_date = new Date(today.getTime() + expires);
  92.  
  93.         c.push('expires=' + expires_date.toGMTString());
  94.     }
  95.  
  96.     if (path)   c.push('path=' + path);
  97.     if (domain) c.push('domain=' + domain);
  98.     if (secure) c.push('secure');
  99.  
  100.     document.cookie = c.join(';');
  101. }
  102.  
  103. function deleteCookie(name, path, domain) {
  104.     if (getCookieValue(name)) {
  105.         let c = [name + '='];
  106.  
  107.         if (path)   c.push('path=' + path);
  108.         if (domain) c.push('domain=' + domain);
  109.  
  110.         c.push('expires=Thu, 01-Jan-1970 00:00:01 GMT');
  111.  
  112.         document.cookie = c.join(';');
  113.     }
  114. }
  115.  
  116. // Разбор строк запросов
  117. // Предполагается, что мы работаем с "?post=1234&action=edit"
  118.  
  119. var urlParams = new URLSearchParams(window.location.search);
  120. console.log(urlParams.has('post')); // true
  121. console.log(urlParams.get('action')); // "edit"
  122. console.log(urlParams.getAll('action')); // ["edit"]
  123. console.log(urlParams.toString()); // "?post=1234&action=edit"
  124. console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
  125.  
  126. // Date Difference - Days
  127. let date1 = new Date("10/13/1975");
  128. let date2 = new Date("10/14/1979");
  129. let diff  = Math.abs(date2.getTime() - date1.getTime()) / 86400000;
  130.  
  131. // URL Encode
  132. function urlencode (str) {
  133.     str = (str + '').toString();
  134.     return encodeURIComponent(str)
  135.            .replace(/!/g, '%21')
  136.            .replace(/'/g, '%27')
  137.            .replace(/\(/g, '%28')
  138.            .replace(/\)/g, '%29')
  139.            .replace(/\*/g, '%2A')
  140.            .replace(/%20/g, '+');
  141. }
  142.  
  143. // URL Decode
  144. function urldecode(str) {
  145.     return decodeURIComponent((str + '').replace(/\+/g, '%20'));
  146. }
  147.  
  148. // Sort Elements By Certain Property
  149. const sortBy = (arr, key) => arr.sort((a, b) => a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0);
  150.  
  151. const lessons = [{ position: 1, name: "Intro" }, { position: 0, name: "Basics" }];
  152. sortBy(lessons, 'position');
  153.  
  154. // Group array elements by specific criteria
  155. const items = [
  156.     { category : 'fruit', name : 'apple' },
  157.     { category : 'fruit', name : 'pear' },
  158.     { category : 'veg',   name : 'carrot' }
  159. ];
  160.  
  161. const grouped = Object.groupBy(items, (item) => item.category);
  162. console.log(grouped);
  163.  
  164. // Check if Arrays/Objects are Equal
  165. const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
  166.  
  167. // Count Number of Occurrences
  168. const countOccurrences = (arr, value) => arr.reduce((a, v) => (v === value ? a + 1 : a), 0);
  169.  
  170. const pollResponses = ["Yes", "Yes", "No"];
  171. const response = "Yes";
  172.  
  173. countOccurrences(pollResponses, response); // 2
  174.  
  175. // Wait for a Certain Amount of Time
  176. const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
  177. wait(2000).then(() => goToSignupPage());
  178.  
  179. // Insert an Element at a Certain Position
  180. const insert = (arr, index, newItem) => [...arr.slice(0, index), newItem, ...arr.slice(index)];
  181.  
  182. const items = [1, 2, 4, 5];
  183. insert(items, 2, 3); // [1, 2, 3, 4, 5]
  184.  
  185. // Copy to Clipboard
  186. const copyToClipboard = (text) => navigator.clipboard.writeText(text);
  187. copyToClipboard("This Sring is Copied To Clipboard");
  188.  
  189. // Strip HTML
  190. const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
  191. stripHtml('<h1>Hello <strong>World</strong>!!!</h1>'); // Hello World!!!
  192.  
  193. // Получение параметров запроса из URL
  194. const getParameters = (URL) => JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}');
  195.  
  196. getParameters("https://www.google.de/search?q=cars&start=40"); // { q: 'cars', start: '40' }
  197.  
  198. // Нахождение максимального и минимального числа в массиве
  199. const arr = [2, 8, 15, 4];
  200. Math.max(...arr); // 15
  201. Math.min(...arr); // 2
  202.  
  203. // Проверка типа
  204. function isOfType(x) {
  205.     // создаем пустую коллекцию без прототипа
  206.     const type = Object.create(null);
  207.  
  208.     // проверка на null
  209.     type.null = (null === x);
  210.     // проверка на undefined
  211.     type.undefined = (undefined === x);
  212.     // проверка на nil - сюда относятся и null, и undefined
  213.     type.nil = type.null || type.undefined;
  214.  
  215.     // проверка на строку и литерал String:
  216.     // 's', "S", new String()
  217.     type.string = !type.nil && (typeof x === 'string' || x instanceof String);
  218.  
  219.     // проверка на число и литерал числа: 12, 30.5, new Number()
  220.     // для NaN и Infinity оператор typeof также возвращает 'number',
  221.     // поэтому их нужно исключить
  222.     type.number = !type.nil && ((!isNaN(x) && isFinite(x) && typeof x === 'number') || x instanceof Number);
  223.  
  224.     // проверка на булево значение и литерал Boolean:
  225.     // true, false, new Boolean()
  226.     type.boolean = !type.nil && (typeof x === 'boolean' || x instanceof Boolean);
  227.  
  228.     // проверка на массив
  229.     type.array = type.nil && Array.isArray(x);
  230.  
  231.     // проверка на объект и литерал объекта:
  232.     // {}, new Object(), Object.create(null)
  233.     type.object = ({}).toString.call(x) === '[object Object]';
  234.  
  235.     // проверка на Set
  236.     type.set = !type.nil && x instanceof Set;
  237.     // проверка на Map
  238.     type.map = !type.nil && x instanceof Map;
  239.     // проверка на Date
  240.     type.date = !type.nil && x instanceof Date;
  241.  
  242.     return type;
  243. }
  244.  
  245. // Проверка на пустое значение
  246. function isEmpty(x) {
  247.     let res = null;
  248.  
  249.     if (Array.isArray(x) || typeof x === 'string' || x instanceof String) {
  250.         res = x.length === 0;
  251.     } else if (x instanceof Map || x instanceof Set) {
  252.         res = x.size === 0;
  253.     } else if (({}).toString.call(x) === '[object Object]') {
  254.         res = Object.keys(x).length === 0;
  255.     }
  256.  
  257.     return res;
  258. }
  259.  
  260. // Получение последнего элемента
  261. function lastItem(list) {
  262.  
  263.     if (Array.isArray(list)) {
  264.     } else if (list instanceof Map) {
  265.         list = Array.from(list.values());
  266.     } else if (list instanceof Set) {
  267.         list = Array.from(list);
  268.     }
  269.  
  270.     return list.length ? list.slice(-1)[0] : null;
  271. }
  272.  
  273. // Постоянный опрос (polling)
  274. async function poll(fn, validate, interval = 2500) {
  275.     const resolver = async (resolve, reject) => {
  276.  
  277.         // отлов ошибок, выбрасываемых функцией fn
  278.         try {
  279.             const result = await fn(); // fn необязательно должна возвращть промис
  280.             // вызов валидатора для проверки полученного результата
  281.             const valid = validate(result);
  282.  
  283.             if (valid === true) {
  284.                 resolve(result);
  285.             } else if (valid === false) {
  286.                 setTimeout(resolver, interval, resolve, reject);
  287.             }
  288.           // если валидатор возвращает что-то кроме true/false,
  289.           // опрос прекращается
  290.         } catch (e) {
  291.             reject(e);
  292.         }
  293.     };
  294.  
  295.     return new Promise(resolver);
  296. }
  297.  
  298. // Классы – это синтаксический сахар
  299. function Parent() {
  300.     const privateProp = 12;
  301.     const privateMethod = () => privateProp + 10;
  302.  
  303.     this.publicMethod = (x = 0) => privateMethod() + x;
  304.     this.publicProp = 10;
  305. }
  306.  
  307. class Child extends Parent {
  308.     myProp = 20;
  309. }
  310.  
  311. const child = new Child();
  312.  
  313. console.log(
  314.     child.myProp, // 20
  315.     child.publicProp, // 10
  316.     child.publicMethod(40), // 62
  317.     child.privateProp, // undefined
  318.     child.privateMethod(), // ошибка "child.privateMethod is not a function"
  319. );
  320.  
  321. // Сложный конструктор
  322. function Employee() {
  323.     this.profession = 'Software Engineer';
  324.     this.salary = '$150000';
  325. }
  326.  
  327. function DeveloperFreelancer() {
  328.     this.programmingLanguages = ['JavaScript', 'Python', 'Swift'];
  329.     this.avgPerHour = '$100';
  330. }
  331.  
  332. function Engineer(name) {
  333.     this.name = name;
  334.     this.freelancer = {};
  335.  
  336.     Employee.apply(this);
  337.     DeveloperFreelancer.apply(this.freelancer);
  338. }
  339.  
  340. const john = new Enginerr('John Doe');
  341.  
  342. console.log(
  343.     john.name, // 'John Doe'
  344.     john.profession, // 'Software Engineer'
  345.     john.salary, // '$150000'
  346.     john.freelancer,
  347.     // { programmingLanguages: ['JavaScript', 'Python', 'Swift'], avgPerHour: '$100' }
  348. );
  349.  
  350. async function fetchData() {
  351.     try {
  352.         const response = await fetch('https://api.example.com/data');
  353.         return await response.json();
  354.     } catch (error) {
  355.         console.error('Fetch error:', error);
  356.     }
  357. }
  358.  
  359. function fetchWithTimeout(url, options = {}, timeout = 5000) {
  360.     // Creates a promise that rejects in <timeout> milliseconds
  361.     const timeoutPromise = new Promise((_, reject) =>
  362.         setTimeout(() => reject(new Error('Request timed out')), timeout)
  363.     );
  364.  
  365.     // Start fetch request and race it against the timeout
  366.     return Promise.race([ fetch(url, options), timeoutPromise) ]);
  367. }
  368. // Usage example
  369. fetchWithTimeout('https://api.example.com/data', {}, 5000)
  370. .then(response => response.json())
  371. .then(data => console.log(data))
  372. .catch(error => console.error('Error:', error));
  373.  
  374. // Debouncing  — это когда функция срабатывает только после того, как действие пользователя завершилось
  375. // и прошло определённое время без новых событий
  376. function debounce(func, delay) {
  377.     let timeout;
  378.     return function(...args) {
  379.         clearTimeout(timeout);
  380.         timeout = setTimeout(() => func.apply(this, args), delay);
  381.     };
  382. }
  383.  
  384. function searchQuery(query) { console.log('Seaching for:', query); }
  385. const debouncedSearch = debounce(searchQuery, 300);
  386. document.getElementById('searchInput').addEventListener('input', (event) => { debouncedSearch(event.target.value); });
  387.  
  388. // Throttling — функция выполняется не чаще, чем один раз за установленный промежуток времени
  389. function throttle(func, limit) {
  390.     let inThrottle;
  391.     return function(...args) {
  392.         if (!inThrottle) {
  393.             func.apply(this, args);
  394.             inThrottle = true;
  395.             setTimeout(() => inThrottle = false, limit);
  396.         }
  397.     };
  398. }
  399.  
  400. function logScrollPosition() { console.log('Scroll position:', window.scrollY); }
  401. const throttledScroll = throttle(logScrollPosition, 200);
  402. window.addEventListener('scroll', throttledScroll);
  403.  
  404. // Распаковать вложенный массив в одномерный
  405. function flattenArray(arr) {
  406.     return arr.reduce((acc, val) =>
  407.         Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []
  408.     );
  409. }
  410.  
  411. // Глубокое копирование объекта позволяет создать его полную независимую копию, не изменяя оригинал
  412. function deepClone(obj) {
  413.     return JSON.parse(JSON.stringify(obj));
  414. }
Advertisement
Add Comment
Please, Sign In to add comment