在JavaScript生态中,函数封装能力直接决定代码质量层级。优秀的函数设计可将复杂业务逻辑转化为可组合的原子单元,使代码具备以下特性:
本文将深入剖析专业开发者封装函数的7大核心策略,通过实战案例展示高质量代码的构建过程。
// 反模式:混杂职责
function processUserData(userData) {
// 验证
if (!userData.name) throw new Error(...);
// 格式化
const formattedData = {
name: userData.name.trim(),
age: parseInt(userData.age)
};
// 存储
localStorage.setItem('user', JSON.stringify(formattedData));
}
// 优化方案:职责拆分
const validateUser = (data) => {/* 纯验证逻辑 */};
const formatUserData = (data) => {/* 纯格式化逻辑 */};
const persistData = (data) => {/* 纯存储逻辑 */};
使用策略模式替代复杂条件分支:
const validators = {
email: (value) => /\S+@\S+\.\S+/.test(value),
phone: (value) => /^1[3-9]\d{9}$/.test(value)
};
function validateField(type, value) {
return validators[type] ? validators[type](value) : false;
}
function createChart({
container = '#chart',
width = 800,
height = 600,
data = []
} = {}) {
// 参数校验前置
if (!document.querySelector(container)) {
throw new Error('Invalid container selector');
}
// 主逻辑...
}
function fetchResource(input) {
if (typeof input === 'string') {
return fetch(input);
}
if (input instanceof URL) {
return fetch(input.href);
}
if (input instanceof Request) {
return fetch(input);
}
throw new TypeError('Unsupported input type');
}
function safeParseJSON(str) {
try {
return JSON.parse(str);
} catch (error) {
console.error(`JSON解析失败: ${str}`);
return null;
}
}
class NetworkError extends Error {
constructor(message) {
super(message);
this.name = 'NetworkError';
}
}
class ValidationError extends Error {
constructor(field) {
super(`${field} validation failed`);
this.name = 'ValidationError';
this.field = field;
}
}
const createLogger = (namespace) => {
return (message, level = 'info') => {
console[level](`[${namespace}] ${message}`);
};
};
const apiLogger = createLogger('API');
apiLogger('Request sent', 'debug');
const compose = (...fns) => (initialVal) =>
fns.reduceRight((val, fn) => fn(val), initialVal);
const formatPrice = compose(
num => `$${num}`,
num => num.toFixed(2),
num => num * 1.1 // 加税
);
console.log(formatPrice(100)); // $110.00
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 factorial = memoize(n => {
if (n === 0) return 1;
return n * factorial(n - 1);
});
function createLazyLoader(loadFn) {
let promise = null;
return () => {
if (!promise) {
promise = loadFn().then(module => {
return module;
});
}
return promise;
};
}
function createPaymentProcessor({ db, logger = console }) {
return {
async process(order) {
try {
const result = await db.save(order);
logger.log('Payment processed:', order.id);
return result;
} catch (error) {
logger.error('Payment failed:', error);
throw error;
}
}
};
}
function calculateCartTotal(items, discount = 0) {
return items.reduce((sum, item) => {
return sum + (item.price * item.quantity);
}, 0) * (1 - discount);
}
/**
* 格式化持续时间
* @param {number} milliseconds - 毫秒数
* @param {object} [options] - 配置项
* @param {boolean} [options.showMs] - 是否显示毫秒
* @returns {string} 格式化后的时间字符串
*/
function formatDuration(milliseconds, { showMs = false } = {}) {
// 实现逻辑...
}
interface PaginationOptions<T> {
pageSize: number;
currentPage: number;
formatter?: (item: T) => unknown;
}
function paginate<T>(items: T[], options: PaginationOptions<T>) {
// 实现逻辑...
}
优秀的函数封装需要持续迭代优化,重点把握:
通过遵循这些原则,开发者能构建出适应复杂业务场景的健壮函数库,为大型应用奠定坚实基础。记住:每个函数都是一个微型API,需要以产品思维精心打磨。