Cache
Class | Source Code
Facilitates caching generic data. Generic arguments allow setting
the type of the value stored in cache entries as well as the expected
names (defaults to any string) for cache entries.
Entries are added to the cache via set. Entries can later be retrieved
from the cache by calling get with the name originally provided to set.
Once an entry expires, attempts to get it will report a miss and the
expired entry will be removed from the cache.
Note: If an entryLifetimeMs is not configured on the cache instance
during construction, you must set a lifetime on every call to set. If
you exclude a lifetime both at construction and when calling set, your
entries will expire immediately.
Constructors
Section titled “Constructors”new Cache(options: CacheOptions)
Section titled “new Cache(options: CacheOptions)”Accessors
Section titled “Accessors”hasUnexpiredEntries: boolean
Section titled “hasUnexpiredEntries: boolean”isEmpty: boolean
Section titled “isEmpty: boolean”Methods
Section titled “Methods”get(name: TCacheEntryName): undefined | TCacheValue
Section titled “get(name: TCacheEntryName): undefined | TCacheValue”Returns
Section titled “Returns”The value that was last cached under the specified name, or
undefined if the entry is absent or expired.
purge(): void
Section titled “purge(): void”Removes all expired entries from the cache.
Keep in mind that expired entries are automatically cleaned up as they’re
requested via get. You should only be calling this if your use case satisfies all of
the following:
- The cache itself has a long lifetime, high volume, and/or high memory usage.
- Invoking
geton the potentially expired entries is infrequent. - You want to free the memory being used by expired entries.
remove(name: TCacheEntryName): void
Section titled “remove(name: TCacheEntryName): void”Removes the specified entry from the cache.
If an entry with the name doesn’t exist, this is a no-op.
set(name: TCacheEntryName, value: TCacheValue, lifetimeMs: number): void
Section titled “set(name: TCacheEntryName, value: TCacheValue, lifetimeMs: number): void”Sets the specified cache entry to the value. After lifetimeMs,
the entry will be invalid and attempts to get it will result in
a miss. Setting an entry that already exists will overwrite
the existing entry and update its lifetime.
toArray(): [TCacheEntryName, TCacheValue][]
Section titled “toArray(): [TCacheEntryName, TCacheValue][]”Returns
Section titled “Returns”The cache as an array of unexpired entries.
Example
Section titled “Example”const cache = new Cache<number>();
const cacheEntries = cache.toArray();
cacheEntries.forEach(([entryName, entryValue]) => console.log(`${entryName}: ${entryValue}`));wipe(): void
Section titled “wipe(): void”Removes all entries from the cache, including unexpired ones that are still valid.