@jeaf/cache v0.0.3
This package provides features to improve the overall performance of your application by storing the results of expensive function calls and returning the cached result when the same inputs occur again. This method is commonly known as memoization. It can be used to cache results of service calls or file read operations.
Installation
npm install -S @jeaf/cache
yarn add @jeaf/cache
Usage
If you want to enable caching on a stand alone function, you can use the Memoize object directly. The default configuration caches all calls to the function that have the same input.
import {Memoize} from '@jeaf/cache';
// The original expensive function
const sum = (a, b) => a + b;
// A proxy method with caching enabled
const cachedSum = new Memoize(sum);
// Usage
cachedSum.run(1, 2); // Not cached
cachedSum.run(2, 3); // Not cached
cachedSum.run(1, 2); // Cached
cachedSum.run(2, 3); // Cached
Set maximum amount of cached results
In some cases the cached data is to large to store every result. In this case you can configure a maximum amount of cached results.
import {Memoize} from '@jeaf/cache';
// The original expensive function
const sum = (a, b) => a + b;
// A proxy method with caching enabled and size set to 1
const cachedSum = new Memoize(sum, {size: 1});
// Usage
cachedSum.run(1, 2); // Not cached
cachedSum.run(1, 2); // Cached
cachedSum.run(2, 3); // Not cached
cachedSum.run(2, 3); // Cached
cachedSum.run(1, 2); // Not cached
Invalidate cache after a period of time
For results that should be invalidated after a given time period you can use the time configuration parameter.
import {Memoize} from '@jeaf/cache';
// The original expensive function
const sum = (a, b) => a + b;
// A proxy method with caching enabled and max lifetime of 100ms
const cachedSum = new Memoize(sum, {time: 100});
// Usage
cachedSum.run(1, 2); // Not Cached
cachedSum.run(1, 2); // Cached
setTimeout(() => {
cachedSum.run(1, 2); // Not Cached
}, 1000);
Usage as annotion
For methods you can use the @Cache annotation which will behave exactly like the examples above.
import {Cache} from '@jeaf/cache';
class Math {
@Cache({size: 1})
public sum(a,b) {
return a + b;
}
}
// Usage
const math = new Math();
math.sum(1, 2);