Skip to content

About

Creates and caches values under keys. 🏭

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

12 stars

Watchers

0 watching

Forks

Repository files navigation

cached-factory

Creates and caches values under keys. 🏭

πŸ‘ͺ All Contributors: 3 🀝 Code of Conduct: Kept πŸ§ͺ Coverage πŸ“ License: MIT πŸ“¦ npm version πŸ’ͺ TypeScript: Strict

Usage

CachedFactory

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.

import { CachedFactory } from "cached-factory";

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.

import { CachedFactory } from "cached-factory";

const cache = new CachedFactory((key) => ({ key }));

// { key: "banana" }
cache.get("banana");

// true
cache.get("banana") === cache.get("banana");

WeakCachedFactory

The package also exports a WeakCachedFactory class that provides the same behavior as CachedFactory but uses a WeakMap as its underlying data structure. As such, only objects can be used for keys (no primitives), and there is no entries() function.

import { WeakCachedFactory } from "cached-factory";

const cache = new WeakCachedFactory((key: Context) =>
	createSomeResultObject(key),
);

const result = cache.get(someContext);

// true
result === cache.get(someContext);

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

cached-factory is written in TypeScript and ships with strong typing. πŸ’ͺ

πŸ‘‰ Tip: if you're working with noImplicitAny enabled (which is generally a good idea), an inline function provided as an argument to CachedFactory may 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

Christopher Buss
Christopher Buss

πŸ”§
Eli
Eli

πŸ› πŸ€”
Josh Goldberg ✨
Josh Goldberg ✨

πŸ’» πŸ–‹ πŸ“– πŸ€” πŸš‡ 🚧 πŸ“† πŸ”§ πŸ›
michael faith
michael faith

πŸ’» 🚧

πŸ’ This package was templated with create-typescript-app using the Bingo framework.

About

Creates and caches values under keys. 🏭

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

12 stars

Watchers

0 watching

Forks

Used by

Contributors

Languages