-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path3-callback.js
64 lines (57 loc) · 1.64 KB
/
3-callback.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
55
56
57
58
59
60
61
62
63
64
'use strict';
// const wrap = (f, before, after) => (...args) => after(f(...before(...args)));
// const wrapAsync = (f, before, after, beforeCb, afterCb) =>
// (...args) => {
// const callback = args[args.length - 1];
// if (typeof callback === 'function') {
// args[args.length - 1] = (...pars) =>
// afterCb(callback(...beforeCb(...pars)));
// }
// return after(f(...before(...args)));
// };
const wrapFunction = (f) => {
console.log('Wrap function:', f.name);
return (...args) => {
console.log('Called wrapper for:', f.name);
console.dir({ args });
if (args.length > 0) {
const callback = args[args.length - 1];
if (typeof callback === 'function') {
args[args.length - 1] = (...args) => {
console.log('Callback:', f.name);
const cbRes = callback(...args);
console.log('Callback results:', cbRes);
return cbRes;
};
}
}
console.log('Call:', f.name);
console.dir(args);
const result = f(...args);
console.log('Ended wrapper for:', f.name);
console.dir({ result });
return result;
};
};
const cloneInterface = (anInterface) => {
const clone = {};
const keys = Object.keys(anInterface);
for (const key of keys) {
const fn = anInterface[key];
clone[key] = wrapFunction(fn);
}
return clone;
};
// Usage
const interfaceName = {
methodName(par1, par2, callback) {
console.dir({ par1, par2 });
callback(null, { field: 'value' });
return par1;
},
};
const cloned = cloneInterface(interfaceName);
cloned.methodName('Uno', 'Due', (err, data) => {
console.log({ err, data });
return true;
});