节点 Class 中的 Memoizee 实例方法

Memoizee instance method in node Class

我正在寻找一种使用 Memoizee package 来记忆 class 函数的优雅方法。

在 class 之外,你可以简单地解决这个问题:

const memoize = require('memoizee')

const myFunc = memoize(function myfunc(){ ... })

但在 class 块内,这将不起作用:

class foo {
    constructor(){ ... }

    // Without memoization you would do:
    myFunc(){ ... }

    // Can't do this here:
    myFunc = memoize(function myfunc(){ ... })
}

我可以考虑使用 this. 语法在构造函数中创建它,但这会导致 class 定义不太统一,因为非记忆方法将在构造函数外部声明:

class foo {
    constructor(){
        // Inside for memoized:
        this.myFunc = memoize(function myfunc(){ ... }) 
    }

    // Outside for non-memoized:
    otherFunc(){ ... }
}

您将如何包装实例方法?

根据您 运行 代码的方式以及您是否使用转译步骤,也许您可​​以使用 memoized-class-decorator 和:

class foo {
    constructor () { ... }

    // Without memoization:
    myFunc () { ... }

    // With memoization:
    @memoize
    myFunc () { ... }
}

memoizee 中有专门的方法处理。参见:https://github.com/medikoo/memoizee#memoizing-methods

它仍然不适用于本机 class 语法,此时您最好做的是:

const memoizeMethods = require('memoizee/methods');

class Foo {
  // .. non memoized definitions
}
Object.defineProperties(Foo.prototype, memoizeMethods({
  // Memoized definitions, need to be provided via descriptors.
  // To make it less verbose you can use packages as 'd':
  // https://www.npmjs.com/package/d
  myFunc: {
    configurable: true,
    writable: true,
    enumerable: false,
    value: function () { ... }
 }
});

可以在构造函数中覆盖自己的方法定义

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