Skip to content
This repository has been archived by the owner on Dec 15, 2021. It is now read-only.

Commit

Permalink
feat(memoizeWithP): Add module memoizeWithP
Browse files Browse the repository at this point in the history
Memoizes a promise returning/async functions result during consecutive calls with same args. Returns
a promise, even from cache.
  • Loading branch information
adambrgmn committed Jan 16, 2018
1 parent c1860c4 commit 0a56468
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/__tests__/memoizeWithP.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import memoizeWithP from '../memoizeWithP';

describe('Core.memoizeWithP', () => {
const memoP = memoizeWithP((...args) => args.join(''));

test('memoizes an async functions result', async () => {
const asyncGetArr = jest.fn(async (a, b) => [a, b]);
const memGetArr = memoP(asyncGetArr);

expect(await memGetArr(1, 2)).toBe(await memGetArr(1, 2));
expect(asyncGetArr).toHaveBeenCalledTimes(1);
});
});
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import map from './map';
import mean from './mean';
import median from './median';
import memoizeWith from './memoizeWith';
import memoizeWithP from './memoizeWithP';
import modulo from './modulo';
import multiply from './multiply';
import negate from './negate';
Expand Down Expand Up @@ -123,6 +124,7 @@ export {
mean,
median,
memoizeWith,
memoizeWithP,
modulo,
multiply,
negate,
Expand Down
25 changes: 25 additions & 0 deletions src/memoizeWithP.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import has from './has';
import prop from './prop';

const memoizeWithP = keyFn => asyncFn => {
const cache = {};
const isCached = key => has(key, cache);
const updateCache = (key, val) => {
cache[key] = val;
};
const getKey = key => new Promise(resolve => resolve(prop(key, cache)));

return (...args) => {
const key = keyFn(...args);
if (!isCached(key)) {
return asyncFn(...args).then(val => {
updateCache(key, val);
return val;
});
}

return getKey(key);
};
};

export { memoizeWithP as default };

0 comments on commit 0a56468

Please sign in to comment.