Skip to content

Instantly share code, notes, and snippets.

@ProGM
Created December 22, 2021 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ProGM/e1ad313b33ccb516fd281f36aecfd3f8 to your computer and use it in GitHub Desktop.
Save ProGM/e1ad313b33ccb516fd281f36aecfd3f8 to your computer and use it in GitHub Desktop.
Cache getters in Angular, similar to computed in Vue, using memoizee
import * as memoizee from 'memoizee';
var objIdMap = new WeakMap, objectCount = 0;
function objectId(object: any){
if (!objIdMap.has(object)) { objIdMap.set(object,++objectCount); }
return objIdMap.get(object);
}
export function cache<T>(cacheKey: keyof T) {
return function(target: any, key: string, descriptor: any) {
target.__$CACHE ??= {};
const newFunction = memoizee(descriptor.value)
descriptor.value = function() {
if (this[cacheKey] !== target.__$CACHE[objectId(this)]?.[key]?.[cacheKey]) {
const _key = objectId(this);
newFunction.clear();
target.__$CACHE[_key] ??= {};
target.__$CACHE[_key][key] ??= {};
target.__$CACHE[_key][key][cacheKey] = this[cacheKey];
}
return newFunction.apply(this, arguments);
}
};
};
import { Component } from '@angular/core';
import { cache } from 'src/utils/cache'
@Component({
selector: 'example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.scss'],
})
export class ExampleComponent {
name = 'John Doe';
age = 45;
get nameAndAgeKey() {
return `${this.name}|${this.age}`;
}
// This getter gets cached using `nameAndAgeKey` as key.
@cache('nameAndAgeKey')
get cachedData() {
return { name: this.name, age: this.age };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment