FRONTEND_1 Telegram 4023
📌Подборка полезных функций, которые пригодятся продвинутым frontend-разработчикам при работе с UI, производительностью и архитектурой


1. Throttle

Контролирует частоту вызова функции, полезно для scroll/resize-событий.


function throttle(fn: Function, delay: number) {
let last = 0;
return (...args: any[]) => {
const now = Date.now();
if (now - last >= delay) {
last = now;
fn(...args);
}
};
}



2. Debounce

Откладывает выполнение функции до окончания серии вызовов.


function debounce(fn: Function, delay: number) {
let timeout: ReturnType<typeof setTimeout>;
return (...args: any[]) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
}



3. Deep Clone (без structuredClone)


function deepClone<T>(obj: T): T {
return JSON.parse(JSON.stringify(obj));
}


Подходит для простых объектов, не содержащих функций, дат и т.п.



4. Safe Access (Optional Chaining + Fallback)


function get<T>(obj: any, path: string, fallback?: T): T {
return path.split('.').reduce((acc, key) => acc?.[key], obj) ?? fallback;
}



5. Wait (async delay)


function wait(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}



6. Generate UUID v4


function uuidv4() {
return crypto.randomUUID(); // нативно в современных браузерах
}



7. Copy to Clipboard


async function copyToClipboard(text: string) {
try {
await navigator.clipboard.writeText(text);
} catch {
const textarea = document.createElement('textarea');
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
}
}



8. Detect Outside Click (для dropdown/modals)


function onClickOutside(element: HTMLElement, callback: () => void) {
function handler(event: MouseEvent) {
if (!element.contains(event.target as Node)) {
callback();
}
}
document.addEventListener('click', handler);
return () => document.removeEventListener('click', handler); // для очистки
}



9. Download File from Blob


function downloadBlob(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}



10. Dynamic Script Loader (например, для внешних SDK)


function loadScript(src: string): Promise<void> {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.async = true;
script.onload = () => resolve();
script.onerror = () => reject(new Error(`Failed to load ${src}`));
document.head.appendChild(script);
});
}


👉 @frontend_1
👍102



tgoop.com/frontend_1/4023
Create:
Last Update:

📌Подборка полезных функций, которые пригодятся продвинутым frontend-разработчикам при работе с UI, производительностью и архитектурой


1. Throttle

Контролирует частоту вызова функции, полезно для scroll/resize-событий.


function throttle(fn: Function, delay: number) {
let last = 0;
return (...args: any[]) => {
const now = Date.now();
if (now - last >= delay) {
last = now;
fn(...args);
}
};
}



2. Debounce

Откладывает выполнение функции до окончания серии вызовов.


function debounce(fn: Function, delay: number) {
let timeout: ReturnType<typeof setTimeout>;
return (...args: any[]) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
}



3. Deep Clone (без structuredClone)


function deepClone<T>(obj: T): T {
return JSON.parse(JSON.stringify(obj));
}


Подходит для простых объектов, не содержащих функций, дат и т.п.



4. Safe Access (Optional Chaining + Fallback)


function get<T>(obj: any, path: string, fallback?: T): T {
return path.split('.').reduce((acc, key) => acc?.[key], obj) ?? fallback;
}



5. Wait (async delay)


function wait(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}



6. Generate UUID v4


function uuidv4() {
return crypto.randomUUID(); // нативно в современных браузерах
}



7. Copy to Clipboard


async function copyToClipboard(text: string) {
try {
await navigator.clipboard.writeText(text);
} catch {
const textarea = document.createElement('textarea');
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
}
}



8. Detect Outside Click (для dropdown/modals)


function onClickOutside(element: HTMLElement, callback: () => void) {
function handler(event: MouseEvent) {
if (!element.contains(event.target as Node)) {
callback();
}
}
document.addEventListener('click', handler);
return () => document.removeEventListener('click', handler); // для очистки
}



9. Download File from Blob


function downloadBlob(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}



10. Dynamic Script Loader (например, для внешних SDK)


function loadScript(src: string): Promise<void> {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.async = true;
script.onload = () => resolve();
script.onerror = () => reject(new Error(`Failed to load ${src}`));
document.head.appendChild(script);
});
}


👉 @frontend_1

BY Frontend разработчик


Share with your friend now:
tgoop.com/frontend_1/4023

View MORE
Open in Telegram


Telegram News

Date: |

Avoid compound hashtags that consist of several words. If you have a hashtag like #marketingnewsinusa, split it into smaller hashtags: “#marketing, #news, #usa. 2How to set up a Telegram channel? (A step-by-step tutorial) The creator of the channel becomes its administrator by default. If you need help managing your channel, you can add more administrators from your subscriber base. You can provide each admin with limited or full rights to manage the channel. For example, you can allow an administrator to publish and edit content while withholding the right to add new subscribers. ‘Ban’ on Telegram When choosing the right name for your Telegram channel, use the language of your target audience. The name must sum up the essence of your channel in 1-3 words. If you’re planning to expand your Telegram audience, it makes sense to incorporate keywords into your name.
from us


Telegram Frontend разработчик
FROM American