Memoized getters in ES6 classes
Alexander Nenashev
Posted on April 23, 2024
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;
}
});
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.
Posted on April 23, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.