Updated cache indexing signature
All checks were successful
Build / Build NPM Project (push) Successful in 26s
Build / Tag Version (push) Successful in 7s

This commit is contained in:
Zakary Timson 2024-09-30 19:39:06 -04:00
parent e40f410830
commit 8094b6507f
3 changed files with 23 additions and 11 deletions

4
package-lock.json generated
View File

@ -1,12 +1,12 @@
{
"name": "@ztimson/utils",
"version": "0.16.9",
"version": "0.16.10",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@ztimson/utils",
"version": "0.16.9",
"version": "0.16.10",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.12",

View File

@ -1,6 +1,6 @@
{
"name": "@ztimson/utils",
"version": "0.16.9",
"version": "0.16.10",
"description": "Utility library",
"author": "Zak Timson",
"license": "MIT",

View File

@ -1,9 +1,11 @@
/**
* Map of data which tracks whether it is a complete collection & offers optional expiry of cached values
*/
export class Cache<K, T> {
private store: any = {};
export class Cache<K extends string | number | symbol, T> {
private store = <Record<K, T>>{};
/** Support index lookups */
[key: string | number | symbol]: T | any;
/** Whether cache is complete */
complete = false;
@ -13,21 +15,22 @@ export class Cache<K, T> {
* @param {keyof T} key Default property to use as primary key
* @param {number} ttl Default expiry in milliseconds
*/
constructor(public readonly key: keyof T, public ttl?: number) {
constructor(public readonly key?: keyof T, public ttl?: number) {
return new Proxy(this, {
get: (target: this, prop: string | symbol) => {
if(prop in target) return (<any>target)[prop];
return target.store[prop];
if (prop in target) return (target as any)[prop];
return target.store[prop as K];
},
set: (target: any, prop: string | symbol, value: T) => {
if(prop in target) target[prop] = value;
else target.store[prop] = value;
set: (target: this, prop: string | symbol, value: any) => {
if (prop in target) (target as any)[prop] = value;
else target.store[prop as K] = value;
return true;
}
});
}
private getKey(value: T): K {
if(!this.key) throw new Error('No key defined');
return <K>value[this.key];
}
@ -101,6 +104,15 @@ export class Cache<K, T> {
return <K[]>Object.keys(this.store);
}
/**
* Get map of cached items
*
* @return {Record<K, T>}
*/
map(): Record<K, T> {
return structuredClone(this.store);
}
/**
* Add an item to the cache manually specifying the key
*