diff --git a/package-lock.json b/package-lock.json index e3e63d0..8e993ef 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index 7b3c60e..46f15da 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ztimson/utils", - "version": "0.16.9", + "version": "0.16.10", "description": "Utility library", "author": "Zak Timson", "license": "MIT", diff --git a/src/cache.ts b/src/cache.ts index 6d8dcd3..8624f35 100644 --- a/src/cache.ts +++ b/src/cache.ts @@ -1,9 +1,11 @@ /** * Map of data which tracks whether it is a complete collection & offers optional expiry of cached values */ -export class Cache { - private store: any = {}; +export class Cache { + private store = >{}; + /** Support index lookups */ + [key: string | number | symbol]: T | any; /** Whether cache is complete */ complete = false; @@ -13,21 +15,22 @@ export class Cache { * @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 (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 value[this.key]; } @@ -101,6 +104,15 @@ export class Cache { return Object.keys(this.store); } + /** + * Get map of cached items + * + * @return {Record} + */ + map(): Record { + return structuredClone(this.store); + } + /** * Add an item to the cache manually specifying the key *