Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Retrieving query string values via jQuery
- // 'name' - your query string name if there is multiple string
- function getValue(name) {
- return decodeURI((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]);
- }
- // Device detection
- if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
- // Do something
- } else {
- // Do something else
- }
- // date validator
- function isValidDate(value, userFormat) {
- // Set default format if format is not provided
- userFormat = userFormat || 'mm/dd/yyyy';
- // Find custom delimiter by excluding
- // month, day and year characters
- let delimiter = /[^mdy]/.exec(userFormat)[0];
- // Create an array with month, day and year
- // so we know the format order by index
- let theFormat = userFormat.split(delimiter);
- // Create array from user date
- let theDate = value.split(delimiter);
- function isDate(date, format) {
- let m, d, y, i = 0, len = format.length, f;
- for (i; i < len; i ++) {
- f = format[i];
- if (/m/.test(f)) m = date[i];
- if (/d/.test(f)) d = date[i];
- if (/y/.test(f)) y = date[i];
- }
- return (
- m > 0 && m < 13 &&
- y && y.length === 4 &&
- d > 0 &&
- // Check if it's a valid day of the month
- d <= (new Date(y, m, 0)).getDate()
- );
- }
- return isDate(theDate, theFormat);
- }
- // Javascript склонение
- // PluralNumber(days, ‘ д’, ‘ень’, ‘ня’, ‘ней’)
- function PluralNumber(count, arg0, arg1, arg2, arg3) {
- let result = arg0;
- let last_digit = count % 10;
- let last_two_digits = count % 100;
- if (last_digit == 1 && last_two_digits != 11) {
- result += arg1;
- } else if (
- (last_digit == 2 && last_two_digits != 12)
- ||
- (last_digit == 3 && last_two_digits != 13)
- ||
- (last_digit == 4 && last_two_digits != 14)
- ) {
- result += arg2;
- } else {
- result += arg3;
- }
- return result;
- }
- // Get cookie value
- const getCookieValue = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
- getCookieValue('_ga'); // Результат: "GA1.2.1929736587.1601974046"
- // Clear all cookies
- const clearCookies = document.cookie.split(';').forEach(
- cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`)
- );
- function setCookie(name, value, expires, path, domain, secure) {
- let c = [name + '=' + escape(value)];
- if (expires) {
- expires = expires * 1000 * 60 * 60 * 24;
- let today = new Date();
- today.setTime(today.getTime());
- let expires_date = new Date(today.getTime() + expires);
- c.push('expires=' + expires_date.toGMTString());
- }
- if (path) c.push('path=' + path);
- if (domain) c.push('domain=' + domain);
- if (secure) c.push('secure');
- document.cookie = c.join(';');
- }
- function deleteCookie(name, path, domain) {
- if (getCookieValue(name)) {
- let c = [name + '='];
- if (path) c.push('path=' + path);
- if (domain) c.push('domain=' + domain);
- c.push('expires=Thu, 01-Jan-1970 00:00:01 GMT');
- document.cookie = c.join(';');
- }
- }
- // Разбор строк запросов
- // Предполагается, что мы работаем с "?post=1234&action=edit"
- var urlParams = new URLSearchParams(window.location.search);
- console.log(urlParams.has('post')); // true
- console.log(urlParams.get('action')); // "edit"
- console.log(urlParams.getAll('action')); // ["edit"]
- console.log(urlParams.toString()); // "?post=1234&action=edit"
- console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
- // Date Difference - Days
- let date1 = new Date("10/13/1975");
- let date2 = new Date("10/14/1979");
- let diff = Math.abs(date2.getTime() - date1.getTime()) / 86400000;
- // URL Encode
- function urlencode (str) {
- str = (str + '').toString();
- return encodeURIComponent(str)
- .replace(/!/g, '%21')
- .replace(/'/g, '%27')
- .replace(/\(/g, '%28')
- .replace(/\)/g, '%29')
- .replace(/\*/g, '%2A')
- .replace(/%20/g, '+');
- }
- // URL Decode
- function urldecode(str) {
- return decodeURIComponent((str + '').replace(/\+/g, '%20'));
- }
- // Sort Elements By Certain Property
- const sortBy = (arr, key) => arr.sort((a, b) => a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0);
- const lessons = [{ position: 1, name: "Intro" }, { position: 0, name: "Basics" }];
- sortBy(lessons, 'position');
- // Group array elements by specific criteria
- const items = [
- { category : 'fruit', name : 'apple' },
- { category : 'fruit', name : 'pear' },
- { category : 'veg', name : 'carrot' }
- ];
- const grouped = Object.groupBy(items, (item) => item.category);
- console.log(grouped);
- // Check if Arrays/Objects are Equal
- const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
- // Count Number of Occurrences
- const countOccurrences = (arr, value) => arr.reduce((a, v) => (v === value ? a + 1 : a), 0);
- const pollResponses = ["Yes", "Yes", "No"];
- const response = "Yes";
- countOccurrences(pollResponses, response); // 2
- // Wait for a Certain Amount of Time
- const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
- wait(2000).then(() => goToSignupPage());
- // Insert an Element at a Certain Position
- const insert = (arr, index, newItem) => [...arr.slice(0, index), newItem, ...arr.slice(index)];
- const items = [1, 2, 4, 5];
- insert(items, 2, 3); // [1, 2, 3, 4, 5]
- // Copy to Clipboard
- const copyToClipboard = (text) => navigator.clipboard.writeText(text);
- copyToClipboard("This Sring is Copied To Clipboard");
- // Strip HTML
- const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
- stripHtml('<h1>Hello <strong>World</strong>!!!</h1>'); // Hello World!!!
- // Получение параметров запроса из URL
- const getParameters = (URL) => JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}');
- getParameters("https://www.google.de/search?q=cars&start=40"); // { q: 'cars', start: '40' }
- // Нахождение максимального и минимального числа в массиве
- const arr = [2, 8, 15, 4];
- Math.max(...arr); // 15
- Math.min(...arr); // 2
- // Проверка типа
- function isOfType(x) {
- // создаем пустую коллекцию без прототипа
- const type = Object.create(null);
- // проверка на null
- type.null = (null === x);
- // проверка на undefined
- type.undefined = (undefined === x);
- // проверка на nil - сюда относятся и null, и undefined
- type.nil = type.null || type.undefined;
- // проверка на строку и литерал String:
- // 's', "S", new String()
- type.string = !type.nil && (typeof x === 'string' || x instanceof String);
- // проверка на число и литерал числа: 12, 30.5, new Number()
- // для NaN и Infinity оператор typeof также возвращает 'number',
- // поэтому их нужно исключить
- type.number = !type.nil && ((!isNaN(x) && isFinite(x) && typeof x === 'number') || x instanceof Number);
- // проверка на булево значение и литерал Boolean:
- // true, false, new Boolean()
- type.boolean = !type.nil && (typeof x === 'boolean' || x instanceof Boolean);
- // проверка на массив
- type.array = type.nil && Array.isArray(x);
- // проверка на объект и литерал объекта:
- // {}, new Object(), Object.create(null)
- type.object = ({}).toString.call(x) === '[object Object]';
- // проверка на Set
- type.set = !type.nil && x instanceof Set;
- // проверка на Map
- type.map = !type.nil && x instanceof Map;
- // проверка на Date
- type.date = !type.nil && x instanceof Date;
- return type;
- }
- // Проверка на пустое значение
- function isEmpty(x) {
- let res = null;
- if (Array.isArray(x) || typeof x === 'string' || x instanceof String) {
- res = x.length === 0;
- } else if (x instanceof Map || x instanceof Set) {
- res = x.size === 0;
- } else if (({}).toString.call(x) === '[object Object]') {
- res = Object.keys(x).length === 0;
- }
- return res;
- }
- // Получение последнего элемента
- function lastItem(list) {
- if (Array.isArray(list)) {
- } else if (list instanceof Map) {
- list = Array.from(list.values());
- } else if (list instanceof Set) {
- list = Array.from(list);
- }
- return list.length ? list.slice(-1)[0] : null;
- }
- // Постоянный опрос (polling)
- async function poll(fn, validate, interval = 2500) {
- const resolver = async (resolve, reject) => {
- // отлов ошибок, выбрасываемых функцией fn
- try {
- const result = await fn(); // fn необязательно должна возвращть промис
- // вызов валидатора для проверки полученного результата
- const valid = validate(result);
- if (valid === true) {
- resolve(result);
- } else if (valid === false) {
- setTimeout(resolver, interval, resolve, reject);
- }
- // если валидатор возвращает что-то кроме true/false,
- // опрос прекращается
- } catch (e) {
- reject(e);
- }
- };
- return new Promise(resolver);
- }
- // Классы – это синтаксический сахар
- function Parent() {
- const privateProp = 12;
- const privateMethod = () => privateProp + 10;
- this.publicMethod = (x = 0) => privateMethod() + x;
- this.publicProp = 10;
- }
- class Child extends Parent {
- myProp = 20;
- }
- const child = new Child();
- console.log(
- child.myProp, // 20
- child.publicProp, // 10
- child.publicMethod(40), // 62
- child.privateProp, // undefined
- child.privateMethod(), // ошибка "child.privateMethod is not a function"
- );
- // Сложный конструктор
- function Employee() {
- this.profession = 'Software Engineer';
- this.salary = '$150000';
- }
- function DeveloperFreelancer() {
- this.programmingLanguages = ['JavaScript', 'Python', 'Swift'];
- this.avgPerHour = '$100';
- }
- function Engineer(name) {
- this.name = name;
- this.freelancer = {};
- Employee.apply(this);
- DeveloperFreelancer.apply(this.freelancer);
- }
- const john = new Enginerr('John Doe');
- console.log(
- john.name, // 'John Doe'
- john.profession, // 'Software Engineer'
- john.salary, // '$150000'
- john.freelancer,
- // { programmingLanguages: ['JavaScript', 'Python', 'Swift'], avgPerHour: '$100' }
- );
- async function fetchData() {
- try {
- const response = await fetch('https://api.example.com/data');
- return await response.json();
- } catch (error) {
- console.error('Fetch error:', error);
- }
- }
- function fetchWithTimeout(url, options = {}, timeout = 5000) {
- // Creates a promise that rejects in <timeout> milliseconds
- const timeoutPromise = new Promise((_, reject) =>
- setTimeout(() => reject(new Error('Request timed out')), timeout)
- );
- // Start fetch request and race it against the timeout
- return Promise.race([ fetch(url, options), timeoutPromise) ]);
- }
- // Usage example
- fetchWithTimeout('https://api.example.com/data', {}, 5000)
- .then(response => response.json())
- .then(data => console.log(data))
- .catch(error => console.error('Error:', error));
- // Debouncing — это когда функция срабатывает только после того, как действие пользователя завершилось
- // и прошло определённое время без новых событий
- function debounce(func, delay) {
- let timeout;
- return function(...args) {
- clearTimeout(timeout);
- timeout = setTimeout(() => func.apply(this, args), delay);
- };
- }
- function searchQuery(query) { console.log('Seaching for:', query); }
- const debouncedSearch = debounce(searchQuery, 300);
- document.getElementById('searchInput').addEventListener('input', (event) => { debouncedSearch(event.target.value); });
- // Throttling — функция выполняется не чаще, чем один раз за установленный промежуток времени
- function throttle(func, limit) {
- let inThrottle;
- return function(...args) {
- if (!inThrottle) {
- func.apply(this, args);
- inThrottle = true;
- setTimeout(() => inThrottle = false, limit);
- }
- };
- }
- function logScrollPosition() { console.log('Scroll position:', window.scrollY); }
- const throttledScroll = throttle(logScrollPosition, 200);
- window.addEventListener('scroll', throttledScroll);
- // Распаковать вложенный массив в одномерный
- function flattenArray(arr) {
- return arr.reduce((acc, val) =>
- Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []
- );
- }
- // Глубокое копирование объекта позволяет создать его полную независимую копию, не изменяя оригинал
- function deepClone(obj) {
- return JSON.parse(JSON.stringify(obj));
- }
Advertisement
Add Comment
Please, Sign In to add comment