-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
32 lines (27 loc) · 897 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
'use strict';
const crypto = require('crypto');
const registry = new Map();
function defaultKeyBuilder(func, ...args) {
return `${func.name || 'anonymous'}-${crypto.createHash('sha256').update(JSON.stringify(args)).digest('hex')}`;
}
const defaultOptions = {
keyBuilder: defaultKeyBuilder
};
module.exports = function recycle(func, options = {}) {
return async function (...args) {
options = { ...defaultOptions, ...options };
const identifier = typeof options.keyBuilder === 'function'
? options.keyBuilder(func, ...args) : options.keyBuilder;
if (registry.has(identifier)) {
return registry.get(identifier);
}
const res = func(...args);
registry.set(identifier, res);
try {
await res;
} finally {
registry.delete(identifier);
}
return res;
};
};