Skip to content

Commit

Permalink
fix(utils/cache): saves only last result, otherwise side effects (opt…
Browse files Browse the repository at this point in the history
…ions changes) won't be register
  • Loading branch information
rafamel committed May 4, 2019
1 parent 2439812 commit 0073f48
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 13 deletions.
12 changes: 6 additions & 6 deletions src/utils/cache.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { IOfType } from '~/types';

export default function cache<T>(getId: () => string, fn: () => T): () => T {
const store: IOfType<any> = {};
let id: null | string = null;
let value: null | T = null;

return function() {
const key = getId();
if (store.hasOwnProperty(key)) return store[key];
if (key === id) return value as T;

return (store[key] = fn());
} as any;
id = key;
return (value = fn());
};
}
9 changes: 2 additions & 7 deletions test/utils/cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,14 @@ test(`succeeds`, async () => {
expect(getId).toHaveBeenCalledTimes(3);
expect(cb).toHaveBeenCalledTimes(2);

id = '1';
expect(fn()).toBe('foo');
expect(getId).toHaveBeenCalledTimes(4);
expect(cb).toHaveBeenCalledTimes(2);

id = '3';
cb.mockImplementation(() => Promise.resolve('baz'));
await expect(fn()).resolves.toBe('baz');
expect(getId).toHaveBeenCalledTimes(5);
expect(getId).toHaveBeenCalledTimes(4);
expect(cb).toHaveBeenCalledTimes(3);

await expect(fn()).resolves.toBe('baz');
expect(getId).toHaveBeenCalledTimes(6);
expect(getId).toHaveBeenCalledTimes(5);
expect(cb).toHaveBeenCalledTimes(3);
});

Expand Down

0 comments on commit 0073f48

Please sign in to comment.