面试题答案
一键面试- 优化思路:
- 对于频繁调用的装饰器,缓存装饰后的函数结果。如果相同的参数组合被再次调用,直接返回缓存中的结果,而不是重新执行被装饰的函数并记录日志。
- 关键代码示例:
// 用于缓存结果的Map
const cache: Map<string, any> = new Map();
// 定义日志装饰器
function logDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
const key = `${propertyKey}:${args.join(',')}`;
if (cache.has(key)) {
console.log(`从缓存中获取结果: ${cache.get(key)}`);
return cache.get(key);
}
console.log(`开始执行方法 ${propertyKey}`);
const result = originalMethod.apply(this, args);
console.log(`方法 ${propertyKey} 执行结束`);
cache.set(key, result);
return result;
};
return descriptor;
}
class MyClass {
@logDecorator
myMethod(a: number, b: number) {
return a + b;
}
}
const myObj = new MyClass();
console.log(myObj.myMethod(1, 2));
console.log(myObj.myMethod(1, 2));
上述代码定义了一个日志装饰器logDecorator
,它在方法执行前后添加日志记录,并通过Map
来缓存方法的执行结果。当相同参数的方法被再次调用时,直接从缓存中返回结果,减少了方法执行和日志记录的开销。