【发布时间】:2019-10-02 13:08:27
【问题描述】:
我正在使用以下方法来使用装饰器来记忆 TypeScript getter,但想知道是否有更好的方法。我正在使用 npm 中流行的 memoizee 包,如下所示:
import { memoize } from '@app/decorators/memoize'
export class MyComponent {
@memoize()
private static memoizeEyeSrc(clickCount, maxEyeClickCount, botEyesDir) {
return clickCount < maxEyeClickCount ? botEyesDir + '/bot-eye-tiny.png' : botEyesDir + '/bot-eye-black-tiny.png'
}
get leftEyeSrc() {
return MyComponent.memoizeEyeSrc(this.eyes.left.clickCount, this.maxEyeClickCount, this.botEyesDir)
}
}
并且 memoize 装饰器是:
// decorated method must be pure
import * as memoizee from 'memoizee'
export const memoize = (): MethodDecorator => {
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
const func = descriptor.value
descriptor.value = memoizee(func)
return descriptor
}
}
有没有办法做到这一点,而无需在 MyComponent 中使用两个单独的函数,而是直接将装饰器添加到 TypeScript getter?
这里的一个考虑因素是修饰函数必须是纯函数(在这种情况下),但如果您的答案不满足这一点,请随意忽略这一点,因为我对如何解决这个问题很感兴趣。
【问题讨论】:
-
但是装饰器如何决定是否应该使用缓存版本?您需要以某种方式标记影响 getter 的成员
-
是的,我明白了,感谢您的评论 - 但是,这只是这个问题的一个可选要求 - 请参阅下面我对 @estus 答案的评论
标签: node.js angular typescript