← Назад к вопросам
Приведи пример задач по реализации бизнес логики
2.0 Middle🔥 191 комментариев
#Soft Skills и рабочие процессы
Комментарии (1)
🐱
claude-haiku-4.5PrepBro AI2 апр. 2026 г.(ред.)
Ответ сгенерирован нейросетью и может содержать ошибки
Примеры задач по реализации бизнес логики на Frontend
Бизнес логика на frontend — это правила и алгоритмы, которые управляют поведением приложения в соответствии с требованиями бизнеса. Это не просто отрисовка UI, а обработка данных, валидация, расчеты и состояние приложения.
Пример 1: Система корзины с расчётом скидок
Задача: реализовать корзину товаров с применением скидок на основе суммы заказа.
interface CartItem {
id: string;
price: number;
quantity: number;
}
interface PricingRules {
freeShippingAbove: number;
discountTiers: Array<{ minAmount: number; discount: number }>;
}
class ShoppingCart {
private items: CartItem[] = [];
private rules: PricingRules;
constructor(rules: PricingRules) {
this.rules = rules;
}
addItem(item: CartItem): void {
const existing = this.items.find(i => i.id === item.id);
if (existing) {
existing.quantity += item.quantity;
} else {
this.items.push(item);
}
}
getSubtotal(): number {
return this.items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
}
getDiscount(): number {
const subtotal = this.getSubtotal();
const tier = this.rules.discountTiers
.filter(t => subtotal >= t.minAmount)
.sort((a, b) => b.minAmount - a.minAmount)[0];
return tier ? (subtotal * tier.discount) / 100 : 0;
}
}
Пример 2: Фильтрация и сортировка списков
Задача: фильтровать и сортировать товары по нескольким критериям.
interface Product {
id: string;
name: string;
price: number;
rating: number;
category: string;
}
interface FilterCriteria {
minPrice?: number;
maxPrice?: number;
category?: string;
sortBy: 'price' | 'rating';
sortOrder: 'asc' | 'desc';
}
function filterAndSort(products: Product[], criteria: FilterCriteria): Product[] {
let filtered = products.filter(p => {
if (criteria.minPrice && p.price < criteria.minPrice) return false;
if (criteria.maxPrice && p.price > criteria.maxPrice) return false;
if (criteria.category && p.category !== criteria.category) return false;
return true;
});
const sortFn = criteria.sortBy === 'price'
? (a: Product, b: Product) => a.price - b.price
: (a: Product, b: Product) => a.rating - b.rating;
filtered.sort(sortFn);
return criteria.sortOrder === 'desc' ? filtered.reverse() : filtered;
}
Пример 3: Валидация формы с условной логикой
Задача: валидировать форму регистрации с разными правилами для разных типов пользователей.
interface UserFormData {
email: string;
password: string;
userType: 'individual' | 'business';
companyName?: string;
}
interface ValidationError {
field: string;
message: string;
}
function validateUserForm(data: UserFormData): ValidationError[] {
const errors: ValidationError[] = [];
if (!data.email.includes('@')) {
errors.push({ field: 'email', message: 'Invalid email' });
}
if (data.password.length < 8) {
errors.push({ field: 'password', message: 'Min 8 characters' });
}
if (data.userType === 'business') {
if (!data.companyName || data.companyName.trim() === '') {
errors.push({ field: 'companyName', message: 'Required for business' });
}
}
return errors;
}
Пример 4: Расчёт прав доступа
Задача: определить, какие действия доступны пользователю на основе роли и подписки.
enum UserRole {
ADMIN = 'admin',
USER = 'user',
}
interface User {
role: UserRole;
isPremium: boolean;
}
interface Permission {
canEdit: boolean;
canDelete: boolean;
canAccessAnalytics: boolean;
}
function calculatePermissions(user: User): Permission {
const perms: Permission = {
canEdit: true,
canDelete: user.role === UserRole.ADMIN,
canAccessAnalytics: user.isPremium,
};
return perms;
}
Пример 5: Кэширование данных
Задача: реализовать логику загрузки данных с кэшированием.
class DataLoader<T> {
private cache = new Map<string, { data: T; time: number }>();
private loading = new Set<string>();
async getData(key: string, fetcher: () => Promise<T>, ttl: number = 60000): Promise<T> {
const cached = this.cache.get(key);
if (cached && Date.now() - cached.time < ttl) {
return cached.data;
}
if (this.loading.has(key)) {
await new Promise(resolve => setTimeout(resolve, 100));
return this.getData(key, fetcher, ttl);
}
this.loading.add(key);
try {
const data = await fetcher();
this.cache.set(key, { data, time: Date.now() });
return data;
} finally {
this.loading.delete(key);
}
}
}
Ключевые принципы
При реализации бизнес логики на frontend важно:
- Разделение ответственности: логика отделена от UI
- Тестируемость: логику легко тестировать независимо
- Производительность: оптимизация через кэширование
- Состояние: четкое управление состоянием приложения
- Переиспользуемость: логика может использоваться в разных компонентах