-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxied.js
71 lines (62 loc) · 1.59 KB
/
proxied.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
65
66
67
68
69
70
71
/* eslint strict: 0 */
'use strict';
module.exports = proxied;
/**
* Proxy
*
* @external Proxy
* @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy}
*/
/**
* Returns a callable Proxy object that will call the `fn` function just once.
* Every next time the returned object is called, it will return value from the first call.
*
* The returned Proxy object points to target `fn` function.
*
* @example
* const nuonce = require('nuonce/proxied');
* let i = 0;
* const f = () => ++i;
* f.myProp = 'original';
* const once = nuonce(f);
* once() === once() || console.error('values differ');
* f.myProp = 'changed';
* once.myProp === 'changed' || console.error('proxied property differs from original');
*
* @function
* @memberof module:nuonce
* @param {Function} fn
* @param {Function} [cb] call back once with result, right after first call
* @return {external:Proxy}
*/
function proxied (fn, cb) {
if (typeof fn !== 'function') {
throw new Error('argument must be a function');
}
if (cb && typeof cb !== 'function') {
throw new Error('callback must be a function');
}
var status = {
calls: 0,
value: undefined, // eslint-disable-line no-undefined
cb
};
return new Proxy(fn, {
apply (_, ctx, args) {
if (fn) {
status.value = _.apply(ctx, args);
fn = null;
}
status.calls++;
return status.cb ? status.cb(status) : status.value;
},
construct (_, args) {
if (fn) {
status.value = new _(...args);
fn = null;
}
status.calls++;
return status.cb ? status.cb(status) : status.value;
}
});
}