Sel*_*ish 3 javascript class memoization node.js memoizee
我正在寻找一种优雅的方式来使用Memoizee 包记忆类函数。
在课堂之外,您可以轻松地进行以下操作:
const memoize = require('memoizee')
const myFunc = memoize(function myfunc(){ ... })
Run Code Online (Sandbox Code Playgroud)
但是在类块中,这不起作用:
class foo {
constructor(){ ... }
// Without memoization you would do:
myFunc(){ ... }
// Can't do this here:
myFunc = memoize(function myfunc(){ ... })
}
Run Code Online (Sandbox Code Playgroud)
我可以考虑使用this.语法在构造函数中创建它,但这将导致类定义不太统一,因为非记忆方法将在构造函数之外声明:
class foo {
constructor(){
// Inside for memoized:
this.myFunc = memoize(function myfunc(){ ... })
}
// Outside for non-memoized:
otherFunc(){ ... }
}
Run Code Online (Sandbox Code Playgroud)
你将如何包装一个实例方法?
可以在构造函数中覆盖自己的方法定义
class Foo {
constructor() {
this.bar = _.memoize(this.bar);
}
bar(key) {
return `${key} = ${Math.random()}`;
}
}
const foo = new Foo();
console.log(foo.bar(1));
console.log(foo.bar(1));
console.log(foo.bar(2));
console.log(foo.bar(2));
// Output:
1 = 0.6701435727286942
1 = 0.6701435727286942
2 = 0.38438568145894747
2 = 0.38438568145894747
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2186 次 |
| 最近记录: |