Skip to content

Commit

Permalink
feat(sifrr-storage): add memoize function
Browse files Browse the repository at this point in the history
  • Loading branch information
aadityataparia committed Oct 3, 2019
1 parent 803b5f0 commit f10e638
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class LocalStorage extends Storage {
}

_upsert(data) {
for (let key in data) {
for (const key in data) {
this.store.setItem(this.tableName + '/' + key, this.constructor.stringify(data[key]));
}
return true;
Expand Down
20 changes: 20 additions & 0 deletions packages/browser/sifrr-storage/src/storages/storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,26 @@ class Storage {
return Promise.resolve(this._clear());
}

memoize(func, keyFunc = arg => (typeof arg === 'string' ? arg : stringify(arg))) {
if (typeof func !== 'function') throw Error('Only functions can be memoized');

return (...args) => {
const key = keyFunc(...args);
return this.get(key).then(data => {
if (data[key] === undefined || data[key] === null) {
const resultPromise = func(...args);
if (!(resultPromise instanceof Promise))
throw Error('Only promise returning functions can be memoized');
return resultPromise.then(v => {
return this.set(key, v).then(() => v);
});
} else {
return data[key];
}
});
};
}

isSupported(force = true) {
if (force && (typeof window === 'undefined' || typeof document === 'undefined')) {
return true;
Expand Down
45 changes: 45 additions & 0 deletions packages/browser/sifrr-storage/test/browser/allstorages.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,51 @@ for (let key in SifrrStorage.availableStores) {
expect(result['false']).to.equal(false);
});

it('memoizes with first argument', async () => {
const result = await page.evaluate(async key => {
const storage = new Sifrr.Storage(key);
let i = 0;
const func = async () => i;
const memoized = storage.memoize(func);
const first = await memoized('some');
i++;
const second = await memoized('some', 'lol');
const nonMemoized = await memoized('someNot');
return {
first,
second,
nonMemoized
};
}, key);

expect(result).to.deep.equal({
first: 0,
second: 0,
nonMemoized: 1
});
});

it('memoizes with key function', async () => {
const result = await page.evaluate(async key => {
const storage = new Sifrr.Storage(key);
let i = 0;
const func = async () => i;
const memoized = storage.memoize(func, (a, b) => a + b);
const first = await memoized('some');
i++;
const second = await memoized('some', 'lol');
return {
first,
second
};
}, key);

expect(result).to.deep.equal({
first: 0,
second: 1
});
});

describe('works with all types of data', async () => {
const types = [
'Array',
Expand Down

0 comments on commit f10e638

Please sign in to comment.