| name | modern-javascript-patterns |
| description | Aplica recursos e padrões modernos do ecossistema JavaScript (ES6+). Use ao refatorar código legado, escrever lógicas funcionais ou otimizar aplicações JavaScript. |
Padrões do JavaScript Moderno (Modern JavaScript Patterns)
Guia abrangente para dominar os recursos do JavaScript moderno (ES6+), padrões de programação funcional e as melhores práticas para escrever código limpo, manutenível e performático.
Quando Usar Esta Skill
- Refatorar código JavaScript legado para sintaxe moderna
- Implementar padrões de programação funcional
- Otimizar a performance do JavaScript
- Escrever código manutenível e legível
- Trabalhar com operações assíncronas
- Construir aplicações web modernas
- Migrar de callbacks para Promises/async-await
- Implementar pipelines de transformação de dados
Funcionalidades Principais do ES6+
1. Arrow Functions (Funções de Seta)
Sintaxe e Casos de Uso:
function add(a, b) {
return a + b;
}
const add = (a, b) => a + b;
const double = (x) => x * 2;
const getRandom = () => Math.random();
const processUser = (user) => {
const normalized = user.name.toLowerCase();
return { ...user, name: normalized };
};
const createUser = (name, age) => ({ name, age });
Binding Léxico do 'this':
class Counter {
constructor() {
this.count = 0;
}
increment = () => {
this.count++;
};
incrementTraditional() {
setTimeout(function () {
this.count++;
}, 1000);
}
incrementArrow() {
setTimeout(() => {
this.count++;
}, 1000);
}
}
2. Desestruturação (Destructuring)
Desestruturação de Objetos:
const user = {
id: 1,
name: "John Doe",
email: "john@example.com",
address: {
city: "Nova York",
country: "EUA",
},
};
const { name, email } = user;
const { name: userName, email: userEmail } = user;
const { age = 25 } = user;
const {
address: { city, country },
} = user;
const { id, ...userWithoutId } = user;
function greet({ name, age = 18 }) {
console.log(`Olá ${name}, você tem ${age} anos`);
}
greet(user);
Desestruturação de Arrays:
const numbers = [1, 2, 3, 4, 5];
const [first, second] = numbers;
const [, , third] = numbers;
const [head, ...tail] = numbers;
let a = 1,
b = 2;
[a, b] = [b, a];
function getCoordinates() {
return [10, 20];
}
const [x, y] = getCoordinates();
const [one, two, three = 0] = [1, 2];
3. Operadores Spread e Rest
Spread Operator (Espalhamento):
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
const defaults = { theme: "dark", lang: "pt-br" };
const userPrefs = { theme: "light" };
const settings = { ...defaults, ...userPrefs };
const numbers = [1, 2, 3];
Math.max(...numbers);
const copy = [...arr1];
const objCopy = { ...user };
const newArr = [...arr1, 4, 5];
const newObj = { ...user, age: 30 };
Parâmetros Rest (Rest Parameters):
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
sum(1, 2, 3, 4, 5);
function greet(greeting, ...names) {
return `${greeting} ${names.join(", ")}`;
}
greet("Olá", "João", "Maria", "Pedro");
const { id, ...userData } = user;
const [first, ...rest] = [1, 2, 3, 4, 5];
4. Template Literals
const userName = "John";
const greeting = `Olá, ${userName}!`;
const templateHtml = `
<div>
<h1>${title}</h1>
<p>${content}</p>
</div>
`;
const price = 19.99;
const total = `Total: R$${(price * 1.2).toFixed(2)}`;
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
const value = values[i] || "";
return result + str + `<mark>${value}</mark>`;
}, "");
}
const highlightName = "João";
const age = 30;
const highlightedHtml = highlight`Nome: ${highlightName}, Idade: ${age}`;
5. Literais de Objeto Melhorados (Enhanced Object Literals)
const personName = "John";
const personAge = 30;
const baseUser = { name: personName, age: personAge };
const calculator = {
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
},
};
const field = "email";
const userWithComputedEmail = {
name: "John",
[field]: "john@example.com",
[`get${field.charAt(0).toUpperCase()}${field.slice(1)}`]() {
return this[field];
},
};
const buildUser = (name, ...props) => {
return props.reduce(
(acc, [key, value]) => ({
...acc,
[key]: value,
}),
{ name },
);
};
const generatedUser = buildUser(
"John",
["age", 30],
["email", "john@example.com"],
);
Padrões Assíncronos
1. Promises
Criando e Usando Promises:
const fetchUser = (id) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) {
resolve({ id, name: "John" });
} else {
reject(new Error("ID Inválido"));
}
}, 1000);
});
};
fetchUser(1)
.then((user) => console.log(user))
.catch((error) => console.error(error))
.finally(() => console.log("Pronto"));
fetchUser(1)
.then((user) => fetchUserPosts(user.id))
.then((posts) => processPosts(posts))
.then((result) => console.log(result))
.catch((error) => console.error(error));
Combinadores de Promise:
const promises = [fetchUser(1), fetchUser(2), fetchUser(3)];
Promise.all(promises)
.then((users) => console.log(users))
.catch((error) => console.error("Pelo menos uma falhou:", error));
Promise.allSettled(promises).then((results) => {
results.forEach((result) => {
if (result.status === "fulfilled") {
console.log("Sucesso:", result.value);
} else {
console.log("Erro:", result.reason);
}
});
});
Promise.race(promises)
.then((winner) => console.log("Primeira:", winner))
.catch((error) => console.error(error));
Promise.any(promises)
.then((first) => console.log("Primeiro sucesso:", first))
.catch((error) => console.error("Todas falharam:", error));
2. Async/Await
Uso Básico:
async function fetchUser(id) {
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
return user;
}
async function getUserData(id) {
try {
const user = await fetchUser(id);
const posts = await fetchUserPosts(user.id);
return { user, posts };
} catch (error) {
console.error("Erro ao buscar dados:", error);
throw error;
}
}
async function sequential() {
const user1 = await fetchUser(1);
const user2 = await fetchUser(2);
return [user1, user2];
}
async function parallel() {
const [user1, user2] = await Promise.all([fetchUser(1), fetchUser(2)]);
return [user1, user2];
}
Padrões Avançados:
(async () => {
const result = await someAsyncOperation();
console.log(result);
})();
async function processUsers(userIds) {
for (const id of userIds) {
const user = await fetchUser(id);
await processUser(user);
}
}
const config = await fetch("/config.json").then((r) => r.json());
async function fetchWithRetry(url, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
return await fetch(url);
} catch (error) {
if (i === retries - 1) throw error;
await new Promise((resolve) => setTimeout(resolve, 1000 * (i + 1)));
}
}
}
async function withTimeout(promise, ms) {
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Timeout")), ms),
);
return Promise.race([promise, timeout]);
}
Padrões de Programação Funcional
1. Métodos de Array
Map, Filter, Reduce:
const users = [
{ id: 1, name: "John", age: 30, active: true },
{ id: 2, name: "Jane", age: 25, active: false },
{ id: 3, name: "Bob", age: 35, active: true },
];
const names = users.map((user) => user.name);
const upperNames = users.map((user) => user.name.toUpperCase());
const activeUsers = users.filter((user) => user.active);
const adults = users.filter((user) => user.age >= 18);
const totalAge = users.reduce((sum, user) => sum + user.age, 0);
const avgAge = totalAge / users.length;
const byActive = users.reduce((groups, user) => {
const key = user.active ? "active" : "inactive";
return {
...groups,
[key]: [...(groups[key] || []), user],
};
}, {});
const result = users
.filter((user) => user.active)
.map((user) => user.name)
.sort()
.join(", ");
Métodos de Array Avançados:
const user = users.find((u) => u.id === 2);
const index = users.findIndex((u) => u.name === "Jane");
const hasActive = users.some((u) => u.active);
const allAdults = users.every((u) => u.age >= 18);
const userTags = [
{ name: "John", tags: ["admin", "user"] },
{ name: "Jane", tags: ["user"] },
];
const allTags = userTags.flatMap((u) => u.tags);
const str = "hello";
const chars = Array.from(str);
const numbers = Array.from({ length: 5 }, (_, i) => i + 1);
const arr = Array.of(1, 2, 3);
2. Funções de Alta Ordem (Higher-Order Functions)
Funções como Argumentos:
function forEach(array, callback) {
for (let i = 0; i < array.length; i++) {
callback(array[i], i, array);
}
}
function map(array, transform) {
const result = [];
for (const item of array) {
result.push(transform(item));
}
return result;
}
function filter(array, predicate) {
const result = [];
for (const item of array) {
if (predicate(item)) {
result.push(item);
}
}
return result;
}
Funções Retornando Funções:
const multiply = (a) => (b) => a * b;
const double = multiply(2);
const triple = multiply(3);
console.log(double(5));
console.log(triple(5));
function partial(fn, ...args) {
return (...moreArgs) => fn(...args, ...moreArgs);
}
const add = (a, b, c) => a + b + c;
const add5 = partial(add, 5);
console.log(add5(3, 2));
function memoize(fn) {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn(...args);
cache.set(key, result);
return result;
};
}
const fibonacci = memoize((n) => {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
});
3. Composição e Piping (Composition and Piping)
const compose =
(...fns) =>
(x) =>
fns.reduceRight((acc, fn) => fn(acc), x);
const pipe =
(...fns) =>
(x) =>
fns.reduce((acc, fn) => fn(acc), x);
const addOne = (x) => x + 1;
const double = (x) => x * 2;
const square = (x) => x * x;
const composed = compose(square, double, addOne);
console.log(composed(3));
const piped = pipe(addOne, double, square);
console.log(piped(3));
const processUser = pipe(
(user) => ({ ...user, name: user.name.trim() }),
(user) => ({ ...user, email: user.email.toLowerCase() }),
(user) => ({ ...user, age: parseInt(user.age) }),
);
const user = processUser({
name: " John ",
email: "JOHN@EXAMPLE.COM",
age: "30",
});
4. Funções Puras e Imutabilidade
function addItemImpure(cart, item) {
cart.items.push(item);
cart.total += item.price;
return cart;
}
function addItemPure(cart, item) {
return {
...cart,
items: [...cart.items, item],
total: cart.total + item.price,
};
}
const numbers = [1, 2, 3, 4, 5];
const withSix = [...numbers, 6];
const withoutThree = numbers.filter((n) => n !== 3);
const doubled = numbers.map((n) => (n === 3 ? n * 2 : n));
const user = { name: "John", age: 30 };
const olderUser = { ...user, age: 31 };
const withEmail = { ...user, email: "john@example.com" };
const { age, ...withoutAge } = user;
const deepClone = (obj) => JSON.parse(JSON.stringify(obj));
const clone = structuredClone(user);
Recursos Modernos de Classes (Modern Class Features)
class User {
#password;
id;
name;
static count = 0;
constructor(id, name, password) {
this.id = id;
this.name = name;
this.#password = password;
User.count++;
}
greet() {
return `Olá, ${this.name}`;
}
#hashPassword(password) {
return `hashed_${password}`;
}
get displayName() {
return this.name.toUpperCase();
}
set password(newPassword) {
this.#password = this.#hashPassword(newPassword);
}
static create(id, name, password) {
return new User(id, name, password);
}
}
class Admin extends User {
constructor(id, name, password, role) {
super(id, name, password);
this.role = role;
}
greet() {
return `${super.greet()}, eu sou um admin`;
}
}
Módulos (ES6)
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export class Calculator {
}
export default function multiply(a, b) {
return a * b;
}
import multiply, { PI, add, Calculator } from "./math.js";
import { add as sum } from "./math.js";
import * as Math from "./math.js";
const module = await import("./math.js");
const { add } = await import("./math.js");
if (condition) {
const module = await import("./feature.js");
module.init();
}
Iteradores e Geradores (Iterators and Generators)
const range = {
from: 1,
to: 5,
[Symbol.iterator]() {
return {
current: this.from,
last: this.to,
next() {
if (this.current <= this.last) {
return { done: false, value: this.current++ };
} else {
return { done: true };
}
},
};
},
};
for (const num of range) {
console.log(num);
}
function* rangeGenerator(from, to) {
for (let i = from; i <= to; i++) {
yield i;
}
}
for (const num of rangeGenerator(1, 5)) {
console.log(num);
}
function* fibonacci() {
let [prev, curr] = [0, 1];
while (true) {
yield curr;
[prev, curr] = [curr, prev + curr];
}
}
async function* fetchPages(url) {
let page = 1;
while (true) {
const response = await fetch(`${url}?page=${page}`);
const data = await response.json();
if (data.length === 0) break;
yield data;
page++;
}
}
for await (const page of fetchPages("/api/users")) {
console.log(page);
}
Operadores Modernos (Modern Operators)
const user = { name: "John", address: { city: "NYC" } };
const city = user?.address?.city;
const zipCode = user?.address?.zipCode;
const result = obj.method?.();
const first = arr?.[0];
const defaultFromNull = null ?? "default";
const defaultFromUndefined = undefined ?? "default";
const keepZero = 0 ?? "default";
const keepEmptyString = "" ?? "default";
let a = null;
a ??= "default";
let b = 5;
b ??= 10;
let obj = { count: 0 };
obj.count ||= 1;
obj.count &&= 2;
Otimização de Performance
function debounce(fn, delay) {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
}
const searchDebounced = debounce(search, 300);
function throttle(fn, limit) {
let inThrottle;
return (...args) => {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
const scrollThrottled = throttle(handleScroll, 100);
function* lazyMap(iterable, transform) {
for (const item of iterable) {
yield transform(item);
}
}
const numbers = [1, 2, 3, 4, 5];
const doubled = lazyMap(numbers, (x) => x * 2);
const first = doubled.next().value;
Melhores Práticas
- Use
const por padrão: Use let apenas quando houver necessidade de reatribuição.
- Prefira arrow functions: Especialmente em callbacks.
- Use template literals: Em vez de concatenação de strings com
+.
- Desestruture objetos e arrays: Deixa o código mais limpo.
- Use async/await: Em vez de correntes de Promise (
.then().catch()).
- Evite mutar dados: Use o spread operator e métodos de array.
- Use optional chaining (
?.): Previne o erro "Cannot read property of undefined".
- Use nullish coalescing (
??): Para estabelecer valores padrão.
- Prefira métodos de array (
map, filter, etc.): Sobre loops tradicionais (for, while).
- Use módulos: Para uma melhor organização de código.
- Escreva funções puras: São mais fáceis de testar e raciocinar sobre.
- Use nomes de variáveis significativos: Seu código documenta a si mesmo.
- Mantenha funções pequenas: Princípio da responsabilidade única.
- Trate erros corretamente: Use
try/catch com async/await.
- Use strict mode:
'use strict' (Muitos frameworks modernos já ativam por padrão) para prevenir erros comuns.
Armadilhas Comuns (Common Pitfalls)
- Confusão com binding do
this: Use arrow functions ou bind().
- Usar Async/await sem try/catch: Sempre tenha tratamento de erros.
- Criação desnecessária de Promises: Não faça wrap (
new Promise) de funções que já são assíncronas.
- Mutação de objetos: Use spread operator ou
Object.assign().
- Esquecer de colocar
await: Funções async sempre retornam Promises.
- Bloquear o event loop: Evite ao máximo operações síncronas pesadas.
- Memory leaks (Vazamentos de memória): Limpe event listeners e timers (timeouts/intervals).
- Rejeições de Promise não tratadas: Use
.catch() ou blocos try/catch.
Recursos (Resources)