Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ const value = cache.get('myKey');
// Remove a value from the cache
cache.del('myKey');

// cache a function
const sum = (...nums: number[]) => nums.reduce((total, curr) => total + curr, 0);
const result = cache.cacheFunction('sum', sum, [1, 2, 3]); // 6 (cached)

// Retrieve all key-value pairs from the cache
const allItems = cache.getAll();

Expand Down
27 changes: 27 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,33 @@ class Mmry<T> {
this.cache.set(key, cacheItem);
}

/**
* Caches the return value of a function based on its parameters.
* @param key The key associated with the cached value.
* @param func The function to be cached.
* @param params The parameters of the function.
* @param ttlString The TTL string in the format "<amount> <unit>", e.g., "5 minutes", "5234 seconds".
* @returns The cached value if available, otherwise the return value of the function.
*/
public cacheFunction<U extends (...args: any[]) => any>(
key: string,
func: U,
params: Parameters<U>,
ttlString?: string
): T {
const cacheKey = key + JSON.stringify(params);
const cachedValue = this.get(cacheKey);

if (cachedValue) {
return cachedValue;
}

const funcReturnValue = func(...params);
this.put(cacheKey, funcReturnValue, ttlString);

return funcReturnValue;
}

/**
* Retrieves a value from the cache.
* @param key The key associated with the value.
Expand Down
15 changes: 15 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,19 @@ describe('Mmry', () => {
const result = cache.getAll();
expect(result).toEqual({ key1: 'value1', key2: 'value2' });
});

it('should set a function to be cached and return its return value', () => {
const sum = (...nums: number[]) => nums.reduce((total, curr) => total + curr, 0);
let result = cache.cacheFunction('sum', sum, [1, 2, 3]);
expect(result).toBe(6);
result = cache.cacheFunction('sum', sum, [3, 4, 5]);
expect(result).toBe(12);
});

it('Make sure that the function is caching the function and not duplicating', () => {
const test = (firstName: string, lastName: string) => ({firstName, lastName});
let result1 = cache.cacheFunction('test', test, ['foo', 'bar']);
let result2 = cache.cacheFunction('test', test, ['foo', 'bar']);
expect(result1).toBe(result2);
});
});
Loading