【问题标题】:Memoizee instance method in node Class节点类中的 Memoizee 实例方法
【发布时间】:2017-06-24 15:54:35
【问题描述】:

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

在课堂之外,你可以简单地去做:

const memoize = require('memoizee')

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

但在类块中,这将不起作用:

class foo {
    constructor(){ ... }

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

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

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

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

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

如何包装实例方法?

【问题讨论】:

    标签: javascript node.js class memoization memoizee


    【解决方案1】:

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

    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
    

    【讨论】:

    • 我想虽然与之前的建议类似,但它是最优雅的。谢谢。
    【解决方案2】:

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

    它仍然不适用于原生类语法,此时你可以做的最好的事情是:

    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 () { ... }
     }
    });
    

    【讨论】:

      【解决方案3】:

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

      class foo {
          constructor () { ... }
      
          // Without memoization:
          myFunc () { ... }
      
          // With memoization:
          @memoize
          myFunc () { ... }
      }
      

      【讨论】:

      • 很好的答案,虽然我一直在寻找一些非转换的创造力。谢谢你。 :)
      猜你喜欢
      • 2017-09-03
      • 2021-05-20
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-25
      相关资源
      最近更新 更多