DEV Community

Alexander Nenashev
Alexander Nenashev

Posted on • Edited on

1

Memoized getters in ES6 classes

We've already seen that attaching prototypes could greatly enhance our data, for example we could add a lot of derived data with getters. The problem is that some of calculated properties could be costly and in most cases we'd want to cache them since usually backend data is pretty static, we update it with POSTing to a backend.

Thanks to class inheritance we can provide a base class for our data classes and add any class or/and instance utilities we need:

class BaseObject {
    static defineCachedGetters(getters, options = null) {
        for (const name in getters) {
            Object.defineProperty(this.prototype, name, {
                get() {
                    const value = getters[name].call(this);
                    Object.defineProperty(this, name, Object.assign({
                        value, configurable: true, writable: true
                    }, options));
                    return value;
                },
                configurable: true
            });
        }
    }
};

class User extends BaseObject {

}

User.defineCachedGetters({
    discounts(){
        const out = [];
        /*  
            here we do some expensive calculations and transformations, 
            the result is an array of the user's discounts
        */
        return out;
    }
});

Enter fullscreen mode Exit fullscreen mode

Here we cache a getter's result in an own property of an instance. We make it non enumerable since derived data shouldn't be potentially serialized in a state (JSON.stringify). Later we can delete the property to allow the getter to be evaluated again.

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay