-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathb-universal.js
54 lines (45 loc) · 1.38 KB
/
b-universal.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
'use strict';
const memeizeUniversal = fn => {
const cache = {};
const generateKey = (...args) => args.join('|');
return (...args) => {
let callback;
if (typeof args[args.length - 1] === 'function')
callback = args.pop();
const key = generateKey(...args);
if (cache[key]) {
if (callback) {
console.log(`Async cache: ${key}`);
callback(cache[key].err, cache[key].data);
return;
}
console.log(`Sync cache: ${key}`);
return cache[key];
}
if (callback) {
console.log(`Async calc: ${key}`);
fn(...args, (err, data) => {
cache[key] = { err, data };
callback(err, data);
});
return;
}
console.log(`Sync calc: ${key}`);
cache[key] = fn(...args);
return cache[key];
};
};
//USAGE
const fs = require('fs');
const asyncRead = memeizeUniversal(fs.readFile);
asyncRead('b-universal.js', 'utf8', (err, data) => {
console.log('data length:', data.length);
asyncRead('b-universal.js', 'utf8', (err, data) => {
console.log('data length:', data.length);
});
});
const сум = (a, b) => a + ' => ' + b;
const журба = memeizeUniversal(сум);
console.log(журба('Грушевський', 'Житомир'));
console.log(журба('Скоропадський', 'Мотовилівка'));
console.log(журба('Грушевський', 'Житомир'));