Skip to content

Instantly share code, notes, and snippets.

@jamstooks
Created August 10, 2020 20:05
Show Gist options
  • Save jamstooks/e4d72ee3c9309283b3b035d70c403189 to your computer and use it in GitHub Desktop.
Save jamstooks/e4d72ee3c9309283b3b035d70c403189 to your computer and use it in GitHub Desktop.
Cache a function result in SessionStorage (no matter the properties)
import _ from 'lodash';
/**
* Wraps a function to cache the result
* no matter what props are passed
* only caches the result if it isn't empty
*
* This is just using a closure for caching.
* If the function is declared again, the value will be lost.
*/
export const cacheFunctionResult = (func, key) => {
return (props) => {
const cached = sessionStorage.getItem(key);
console.log(key, cached);
if (cached) {
console.log('using cached value');
return JSON.parse(cached);
}
const result = func(props);
if (!_.isEmpty(result)) {
console.log('caching result');
sessionStorage.setItem(key, JSON.stringify(result));
}
return result;
};
};
import { cacheFunctionResult } from './caching';
describe('Testing Caching Wrapper', () => {
test('Stores result when result is not empty', () => {
const mockFunction = jest.fn((x) => [x, x]);
const cachedFunc = cacheFunctionResult(mockFunction, 'test');
// Sanity check
sessionStorage.setItem('testing', 2);
expect(sessionStorage.getItem('testing')).toEqual('2');
// Run the function initially
let result = cachedFunc(2);
expect(result).toEqual([2, 2]);
// Get the cached result for the same prop
result = cachedFunc(2);
expect(result).toEqual([2, 2]);
// Get the cached result for a different prop
result = cachedFunc(1);
expect(result).toEqual([2, 2]);
expect(mockFunction.mock.calls.length).toBe(1);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment