You're free to add memoization, e.g.
Non memoized,
class NonMemoized {
constructor(prefix) {
this.prefix = prefix;
}
get myFunc() {
return this.prefix + Math.random().toString();
}
}
let nonMemoized = new NonMemoized('new number each time ');
console.log(nonMemoized.myFunc);
console.log(nonMemoized.myFunc);
Memoized, nice for when u want to create an object once and always return the same object (but don't want to create in the constructor because maybe it's not necessary all the time or some other reason)
class MemoizedManually {
constructor(prefix) {
this.prefix = prefix;
}
get myFunc() {
return this._myFunc_ = this._myFunc_ || this.prefix + Math.random().toString();
}
}
let memoizedManually = new MemoizedManually('same number ');
console.log(memoizedManually.myFunc);
console.log(memoizedManually.myFunc);
Lastly, if you have a bunch of functions you want to memoize but don't want to repeat that this.x = this.x || something computation
in each function (which you really shoudln't repeat, as it's not really the job of myFunc
to memoize itself:
class Memoized {
constructor(prefix) {
this.prefix = prefix;
}
get myFunc() {
return this.prefix + Math.random().toString();
}
}
const memoizeGetter = (clazz, functionName) => {
let func = Object.getOwnPropertyDescriptor(clazz.prototype, functionName);
let cacheKey = `_${functionName}-cache_`;
Object.defineProperty(clazz.prototype, functionName, {
get: function () {
return this[cacheKey] = this[cacheKey] || func.get.call(this);
}
});
};
memoizeGetter(Memoized, 'myFunc');
let memoized = new Memoized('also same number ');
console.log(memoized.myFunc);
console.log(memoized.myFunc);
Nice thing about getters is they don't take arguments, so you don't have to worry about ...args
, but do need to worry about binding this