Skip to content

Commit a49b1d0

Browse files
committed
Async memoize first implementation
Refs: #268
1 parent 41ced8c commit a49b1d0

File tree

3 files changed

+90
-1
lines changed

3 files changed

+90
-1
lines changed

lib/memoize.js

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
'use strict';
2+
3+
const util = require('util');
4+
5+
function Memoized() {
6+
}
7+
8+
util.inherits(Memoized, Function);
9+
10+
const memoize = (
11+
// Create memoized function
12+
fn // function, sync or async
13+
// Returns: function, memoized
14+
) => {
15+
const cache = new Map();
16+
17+
const memoized = function(...args) {
18+
const callback = args.pop();
19+
const key = args[0];
20+
const record = cache.get(key);
21+
if (record) {
22+
callback(record.err, record.data);
23+
return;
24+
}
25+
fn(...args, (err, data) => {
26+
cache.set(key, { err, data });
27+
callback(err, data);
28+
});
29+
};
30+
31+
const fields = {
32+
cache,
33+
timeout: 0,
34+
limit: 0,
35+
size: 0,
36+
maxSize: 0
37+
};
38+
39+
Object.setPrototypeOf(memoized, Memoized.prototype);
40+
return Object.assign(memoized, fields);
41+
};
42+
43+
Memoized.prototype.clear = function() {
44+
this.cache.clear();
45+
};
46+
47+
module.exports = {
48+
memoize,
49+
};

metasync.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ const submodules = [
99
'array', // Array utilities
1010
'chain', // Process arrays sync and async array in chain
1111
'collector', // DataCollector and KeyCollector
12-
'queue', // Concurrency
12+
'queue', // Concurrent queue
13+
'memoize', // Async memoization
1314
].map(path => require('./lib/' + path));
1415

1516
const flow = submodules[0].flow;

test/memoize.js

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
'use strict';
2+
3+
const tap = require('tap');
4+
const metasync = require('..');
5+
6+
tap.test('memoize', (test) => {
7+
const storage = {
8+
file1: Buffer.from('file1'),
9+
file2: Buffer.from('file2'),
10+
};
11+
12+
const getData = (file, callback) => {
13+
process.nextTick(() => {
14+
const result = storage[file];
15+
if (result) callback(null, result);
16+
else callback(new Error('File not found'));
17+
});
18+
};
19+
20+
const memoizedGetData = metasync.memoize(getData);
21+
22+
memoizedGetData('file1', (err, data) => {
23+
test.error(err);
24+
test.strictSame(data, storage.file1);
25+
memoizedGetData('file2', (err, data) => {
26+
test.error(err);
27+
test.strictSame(data, storage.file2);
28+
memoizedGetData('file1', (err, data) => {
29+
test.error(err);
30+
test.strictSame(data, storage.file1);
31+
memoizedGetData('file2', (err, data) => {
32+
test.error(err);
33+
test.strictSame(data, storage.file2);
34+
test.end();
35+
});
36+
});
37+
});
38+
});
39+
});

0 commit comments

Comments
 (0)