cached-factory
v0.2.0
Published
Creates and caches values under keys. 🏭
Readme
Usage
cached-factory exports a CachedFactory class that takes in "factory" function in its constructor.
Each time a factory's .get(key) is called with any key for the first time, that factory is used to create a value under the key.
const cache = new CachedFactory((key) => `Cached: ${key}!`);
// "Cached: apple!"
cache.get("apple");Values are cached so that subsequent .get(key) calls with the same key instantly return the same value.
const cache = new CachedFactory((key) => ({ key }));
// { key: "banana" }
cache.get("banana");
// true
cache.get("banana") === cache.get("banana");Asynchronous Factories
CachedFactory does not itself handle Promise logic, but it doesn't have to!
Provided factory functions can themselves be async / return Promise values.
const cache = new CachedFactory(
async (key) => await fetch(`/some/resource?key=${key}`),
);
// Type: Promise<Response>
cache.get("cherry");
// Type: Response
await cache.get("cherry");Other Methods
clear
Clears the cache.
cache.clear();TypeScript
CachedFactory is written in TypeScript and ships with strong typing.
💪
👉 Tip: if you're working with
noImplicitAnyenabled (which is generally a good idea), an inline function provided as an argument toCachedFactorymay need an explicit type annotation for its key.new CachedFactory((key: string) => `Cached: ${key}!`);
Development
See .github/CONTRIBUTING.md, then .github/DEVELOPMENT.md.
Thanks! 🏭
Contributors
💝 This package was templated with
create-typescript-appusing the Bingo framework.
