Created
December 22, 2021 10:57
-
-
Save ProGM/e1ad313b33ccb516fd281f36aecfd3f8 to your computer and use it in GitHub Desktop.
Cache getters in Angular, similar to computed in Vue, using memoizee
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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