Skip to content

Commit

Permalink
Add memoize functor methods
Browse files Browse the repository at this point in the history
PR-URL: #284
  • Loading branch information
tshemsedinov committed Jan 7, 2018
1 parent e6dac98 commit 2fc77e9
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 1 deletion.
19 changes: 18 additions & 1 deletion lib/memoize.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ const memoize = (
timeout: 0,
limit: 0,
size: 0,
maxSize: 0
maxSize: 0,
maxCount: 0,
};

Object.setPrototypeOf(memoized, Memoized.prototype);
Expand All @@ -39,6 +40,22 @@ Memoized.prototype.clear = function() {
this.cache.clear();
};

Memoized.prototype.add = function(key, err, data) {
this.cache.set(key, { err, data });
return this;
};

Memoized.prototype.del = function(key) {
this.cache.delete(key);
return this;
};

Memoized.prototype.get = function(key, callback) {
const record = this.cache.get(key);
callback(record.err, record.data);
return this;
};

module.exports = {
memoize,
};
66 changes: 66 additions & 0 deletions test/memoize.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,69 @@ tap.test('memoize clear cache', (test) => {
});
});
});

tap.test('memoize cache del', (test) => {
const storage = {
file1: Buffer.from('file1'),
};

const getData = (file, callback) => {
process.nextTick(() => {
const result = storage[file];
if (result) callback(null, result);
else callback(new Error('File not found'));
});
};

const memoizedGetData = metasync.memoize(getData);

memoizedGetData('file1', (err, data) => {
test.error(err);
test.strictSame(data, storage.file1);
storage.file1 = Buffer.from('changed');
memoizedGetData.del('file1');
memoizedGetData('file1', (err, data) => {
test.error(err);
test.strictSame(data, Buffer.from('changed'));
test.end();
});
});
});

tap.test('memoize cache add', (test) => {
const getData = (file, callback) => {
process.nextTick(() => {
const result = Buffer.from('added');
callback(null, result);
});
};

const memoizedGetData = metasync.memoize(getData);

const file1 = Buffer.from('added');
memoizedGetData.add('file1', null, file1);
memoizedGetData('file1', (err, data) => {
test.error(err);
test.strictSame(data, Buffer.from('added'));
test.end();
});
});

tap.test('memoize cache get', (test) => {
const getData = (file, callback) => {
process.nextTick(() => {
const result = Buffer.from('added');
callback(null, result);
});
};

const memoizedGetData = metasync.memoize(getData);

const file1 = Buffer.from('added');
memoizedGetData.add('file1', null, file1);
memoizedGetData.get('file1', (err, data) => {
test.error(err);
test.strictSame(data, Buffer.from('added'));
test.end();
});
});

0 comments on commit 2fc77e9

Please sign in to comment.