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.

Image of Wix Studio

2025: Your year to build apps that sell

Dive into hands-on resources and actionable strategies designed to help you build and sell apps on the Wix App Market.

Get started

Top comments (0)

👋 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