Skip to content

Commit

Permalink
Async memoize first implementation
Browse files Browse the repository at this point in the history
Refs: #268
  • Loading branch information
tshemsedinov committed Nov 21, 2017
1 parent 41ced8c commit a49b1d0
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 1 deletion.
49 changes: 49 additions & 0 deletions lib/memoize.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
'use strict';

const util = require('util');

function Memoized() {
}

util.inherits(Memoized, Function);

const memoize = (
// Create memoized function
fn // function, sync or async
// Returns: function, memoized
) => {
const cache = new Map();

const memoized = function(...args) {
const callback = args.pop();
const key = args[0];
const record = cache.get(key);
if (record) {
callback(record.err, record.data);
return;
}
fn(...args, (err, data) => {
cache.set(key, { err, data });
callback(err, data);
});
};

const fields = {
cache,
timeout: 0,
limit: 0,
size: 0,
maxSize: 0
};

Object.setPrototypeOf(memoized, Memoized.prototype);
return Object.assign(memoized, fields);
};

Memoized.prototype.clear = function() {
this.cache.clear();
};

module.exports = {
memoize,
};
3 changes: 2 additions & 1 deletion metasync.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ const submodules = [
'array', // Array utilities
'chain', // Process arrays sync and async array in chain
'collector', // DataCollector and KeyCollector
'queue', // Concurrency
'queue', // Concurrent queue
'memoize', // Async memoization
].map(path => require('./lib/' + path));

const flow = submodules[0].flow;
Expand Down
39 changes: 39 additions & 0 deletions test/memoize.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'use strict';

const tap = require('tap');
const metasync = require('..');

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

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);
memoizedGetData('file2', (err, data) => {
test.error(err);
test.strictSame(data, storage.file2);
memoizedGetData('file1', (err, data) => {
test.error(err);
test.strictSame(data, storage.file1);
memoizedGetData('file2', (err, data) => {
test.error(err);
test.strictSame(data, storage.file2);
test.end();
});
});
});
});
});

0 comments on commit a49b1d0

Please sign in to comment.