Cache
import Cache from '@bbc/front-end-kit/js/managers/Cache';
A generic in-memory cache manager for both synchronous and async (Promise-based) results. Runs a method once and reuses the result until the cache entry expires. Useful for avoiding redundant API calls or expensive computations within a session.
Getting started
import Cache from '@bbc/front-end-kit/js/managers/Cache';
const cache = new Cache();
// sync — method only runs once per key until expiration
const result = cache.runCached('my-key', () => expensiveComputation());
// async — promise only runs once per key until expiration
const data = await cache.runCachedPromise('my-api-call', () => fetch('/api/data').then(r => r.json()));
API
constructor(args = {})
Initialises the Cache instance with an empty internal Map.
Methods
runCached(key, method, options = {})
Runs method() and caches the result under key. On subsequent calls with the same key, returns the cached result until it expires — then re-runs method().
Parameters
key(string): The cache key.method(Function): A function returning the value to cache.options(object, optional):expiration(number, default60000): Time in ms before the cached result is considered stale.
Returns
The return value of method(), or the previously cached result.
runCachedPromise(key, method, options = {})
Same as runCached but for Promise-returning methods. While the Promise is still pending, subsequent calls return the same in-flight Promise. Once resolved, the result is deep-cloned before returning to prevent external mutation of the cached value.
Parameters
key(string): The cache key.method(Function): A function returning aPromise.options(object, optional):expiration(number, default60000): Time in ms before the cached result is considered stale.
Returns
Promise — resolves with a deep clone of the method's resolved value.
External dependencies
- lodash:
cloneDeep: Deep-clones resolved promise results to prevent external mutation.defaultsDeep: Merges caller options over the default expiration.