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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay