caiogondim / fast-memoize.js

:rabbit2: Fastest possible memoization library
https://npm.im/fast-memoize
MIT License
2.58k stars 86 forks source link

Not working with es6 getters #71

Closed ricardomatias closed 5 years ago

ricardomatias commented 5 years ago

I have the following code

    get scale() {
        const createScale = (root, scaleType, noteType) => {
            console.log('MEMOIZE', root, scaleType, noteType);
            return new Scale(root, scaleType, noteType);
        };

        return memoize(createScale)(this._root, this._scaleType, this._noteType);
    }

Even though the arguments are the same, the createScale function is still called twice, thus returning different instances of Scale. Any ideas? Is this specific to ES6 class getters?

planttheidea commented 5 years ago

You appear to be creating a new function and executing it every time scale is called?

ricardomatias commented 5 years ago

Yes, I'm using getters so I only derive the scale, once the someone tries to access the property. As an improvement I thought about adding memoizing, but somehow the function createScale is being triggered, even when the arguments don't change.

planttheidea commented 5 years ago

Well of course it is ... You are creating a new memoized function and executing it every time that scale is called. You should make that function a standalone function (created once, not on every execution) and then it will work as you expect.

ricardomatias commented 5 years ago

That sounds rather obvious.. these getters tied my brain into a knot. Thanks for the help x)