JavaScript系列(12)-- 高阶函数应用
JavaScript高阶函数应用 🚀
今天,让我们深入探讨JavaScript中的高阶函数应用。高阶函数是函数式编程的重要组成部分,掌握它们的应用可以让我们的代码更加优雅和灵活。
高阶函数概述 🌟
💡 小知识:高阶函数是指接受函数作为参数和/或返回函数作为结果的函数。在JavaScript中,函数是"一等公民",这使得高阶函数成为一种强大的编程工具。
常用高阶函数详解 📊
// 1. Array.prototype的高阶函数
function arrayHigherOrderFunctions() {
const numbers = [1, 2, 3, 4, 5];
// map: 转换数组元素
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter: 过滤数组元素
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]
// reduce: 累积计算
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 15
// some: 检查是否存在满足条件的元素
const hasEven = numbers.some(n => n % 2 === 0);
console.log(hasEven); // true
// every: 检查是否所有元素都满足条件
const allPositive = numbers.every(n => n > 0);
console.log(allPositive); // true
// find: 查找第一个满足条件的元素
const firstEven = numbers.find(n => n % 2 === 0);
console.log(firstEven); // 2
// findIndex: 查找第一个满足条件的元素的索引
const firstEvenIndex = numbers.findIndex(n => n % 2 === 0);
console.log(firstEvenIndex); // 1
}
// 2. 自定义高阶函数
function customHigherOrderFunctions() {
// 函数组合
const compose = (...fns) => x =>
fns.reduceRight((acc, fn) => fn(acc), x);
// 函数管道
const pipe = (...fns) => x =>
fns.reduce((acc, fn) => fn(acc), x);
// 函数记忆化
const memoize = fn => {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
};
// 函数节流
const throttle = (fn, delay) => {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
return fn.apply(this, args);
}
};
};
// 函数防抖
const debounce = (fn, delay) => {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), delay);
};
};
}
// 3. 高阶函数链式调用
class FunctionalChain {
constructor(value) {
this.value = value;
}
static of(value) {
return new FunctionalChain(value);
}
map(fn) {
return FunctionalChain.of(fn(this.value));
}
tap(fn) {
fn(this.value);
return this;
}
chain(fn) {
return fn(this.value);
}
value() {
return this.value;
}
}
高阶函数的实际应用 💼
让我们看看高阶函数在实际开发中的一些应用场景:
// 1. 数据处理管道
class DataProcessor {
static createPipeline(...transformers) {
return data => transformers.reduce(
(acc, transformer) => transformer(acc),
data
);
}
// 数据过滤器
static filter(predicate) {
return data => data.filter(predicate);
}
// 数据映射器
static map(transformer) {
return data => data.map(transformer);
}
// 数据分组器
static groupBy(keySelector) {
return data => data.reduce((groups, item) => {
const key = keySelector(item);
(groups[key] = groups[key] || []).push(item);
return groups;
}, {});
}
// 使用示例
static processUserData(users) {
const pipeline = this.createPipeline(
this.filter(user => user.age >= 18),
this.map(user => ({
...user,
fullName: `${user.firstName} ${user.lastName}`
})),
this.groupBy(user => user.country)
);
return pipeline(users);
}
}
// 2. 事件处理系统
class EventSystem {
constructor() {
this.handlers = new Map();
}
// 事件处理器装饰器
static decorate(handler, ...decorators) {
return decorators.reduce(
(acc, decorator) => decorator(acc),
handler
);
}
// 日志装饰器
static withLogging(handler) {
return (...args) => {
console.log('Event handled with args:', args);
const result = handler(...args);
console.log('Event handling result:', result);
return result;
};
}
// 错误处理装饰器
static withErrorHandling(handler) {
return (...args) => {
try {
return handler(...args);
} catch (error) {
console.error('Error in event handler:', error);
throw error;
}
};
}
// 性能监控装饰器
static withPerformanceMonitoring(handler) {
return (...args) => {
const start = performance.now();
const result = handler(...args);
const end = performance.now();
console.log(`Handler took ${end - start}ms`);
return result;
};
}
}
// 3. 中间件系统
class MiddlewareSystem {
constructor() {
this.middlewares = [];
}
// 添加中间件
use(middleware) {
this.middlewares.push(middleware);
return this;
}
// 执行中间件链
execute(initialContext) {
return this.middlewares.reduce(
(promise, middleware) => promise.then(middleware),
Promise.resolve(initialContext)
);
}
// 中间件组合
static compose(...middlewares) {
return context => middlewares.reduce(
(promise, middleware) => promise.then(middleware),
Promise.resolve(context)
);
}
}
高阶函数的性能优化 ⚡
处理高阶函数时的性能优化技巧:
// 1. 缓存优化
class CacheOptimizer {
// 高级缓存策略
static createCachedFunction(fn, {
maxSize = 100,
ttl = 3600000
} = {}) {
const cache = new Map();
const timestamps = new Map();
return (...args) => {
const key = JSON.stringify(args);
const now = Date.now();
// 清理过期缓存
if (timestamps.has(key)) {
const timestamp = timestamps.get(key);
if (now - timestamp > ttl) {
cache.delete(key);
timestamps.delete(key);
}
}
// 缓存命中
if (cache.has(key)) {
return cache.get(key);
}
// 缓存大小控制
if (cache.size >= maxSize) {
const oldestKey = timestamps.keys().next().value;
cache.delete(oldestKey);
timestamps.delete(oldestKey);
}
// 计算新值
const result = fn(...args);
cache.set(key, result);
timestamps.set(key, now);
return result;
};
}
}
// 2. 执行优化
class ExecutionOptimizer {
// 批量处理优化
static batchProcess(fn, batchSize = 1000) {
return async function(items) {
const results = [];
for (let i = 0; i < items.length; i += batchSize) {
const batch = items.slice(i, i + batchSize);
const batchResults = await Promise.all(
batch.map(item => fn(item))
);
results.push(...batchResults);
}
return results;
};
}
// 并发控制
static withConcurrencyLimit(fn, limit = 5) {
const queue = [];
let activeCount = 0;
const processQueue = async () => {
if (activeCount >= limit || queue.length === 0) return;
activeCount++;
const { args, resolve, reject } = queue.shift();
try {
const result = await fn(...args);
resolve(result);
} catch (error) {
reject(error);
} finally {
activeCount--;
processQueue();
}
};
return (...args) => new Promise((resolve, reject) => {
queue.push({ args, resolve, reject });
processQueue();
});
}
}
// 3. 内存优化
class MemoryOptimizer {
// 惰性计算优化
static createLazyFunction(fn) {
let computed = false;
let result;
return (...args) => {
if (!computed) {
result = fn(...args);
computed = true;
}
return result;
};
}
// 内存泄漏防护
static createSafeFunction(fn) {
const weakRefs = new WeakMap();
return (...args) => {
const safeArgs = args.map(arg => {
if (typeof arg === 'object' && arg !== null) {
if (!weakRefs.has(arg)) {
weakRefs.set(arg, new WeakRef(arg));
}
return weakRefs.get(arg).deref();
}
return arg;
});
return fn(...safeArgs);
};
}
}
最佳实践建议 💡
- 高阶函数设计模式
// 1. 装饰器模式
function decoratorPattern() {
// 创建装饰器
const withLogging = fn => (...args) => {
console.log('Calling with args:', args);
const result = fn(...args);
console.log('Returned:', result);
return result;
};
const withTiming = fn => (...args) => {
const start = performance.now();
const result = fn(...args);
const end = performance.now();
console.log(`Execution time: ${end - start}ms`);
return result;
};
const withRetry = (fn, retries = 3) => async (...args) => {
for (let i = 0; i < retries; i++) {
try {
return await fn(...args);
} catch (error) {
if (i === retries - 1) throw error;
console.log(`Retry ${i + 1}/${retries}`);
}
}
};
}
// 2. 策略模式
function strategyPattern() {
const strategies = new Map();
// 注册策略
const registerStrategy = (name, fn) => strategies.set(name, fn);
// 执行策略
const executeStrategy = (name, ...args) => {
const strategy = strategies.get(name);
if (!strategy) throw new Error(`Strategy ${name} not found`);
return strategy(...args);
};
// 组合策略
const composeStrategies = (...names) => (...args) =>
names.reduce((result, name) =>
executeStrategy(name, result),
args
);
}
// 3. 观察者模式
function observerPattern() {
class Observable {
constructor() {
this.observers = new Set();
}
subscribe(observer) {
this.observers.add(observer);
return () => this.observers.delete(observer);
}
notify(data) {
this.observers.forEach(observer => observer(data));
}
pipe(...operators) {
return operators.reduce(
(obs, operator) => operator(obs),
this
);
}
}
}
结语 📝
高阶函数是JavaScript中非常强大的特性,它们能帮助我们写出更加模块化和可复用的代码。我们学习了:
- 常用的高阶函数及其应用
- 自定义高阶函数的实现
- 实际应用场景
- 性能优化技巧
- 最佳实践和设计模式
💡 学习建议:在使用高阶函数时,要注意平衡抽象程度和代码可读性。过度使用高阶函数可能会使代码难以理解和维护。同时,要注意性能影响,合理使用缓存和优化策略。
如果你觉得这篇文章有帮助,欢迎点赞收藏,也期待在评论区看到你的想法和建议!👇
终身学习,共同成长。
咱们下一期见
💻