-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex2.js
More file actions
54 lines (45 loc) · 1.34 KB
/
ex2.js
File metadata and controls
54 lines (45 loc) · 1.34 KB
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';
/*
Problem:
Implement `wrapCallable(fn, { before, after })`.
Behavior:
- Return a Proxy for callable/constructable `fn`.
- On function call:
- call `before(args)` first
- invoke original function preserving `this`
- call `after(result)`
- return result
- On constructor call (`new`):
- call `before(args)`
- construct with correct prototype/newTarget semantics
- call `after(instanceOrReturnedObject)`
- return constructed value
Requirements:
- Must use Reflect.apply and Reflect.construct.
- Must preserve instance checks and prototype behavior.
Starter code is intentionally incorrect:
- apply trap ignores provided thisArg.
- construct trap calls function directly, breaking constructor semantics.
*/
function wrapCallable(fn, { before, after } = {}) {
if (typeof fn !== 'function') {
throw new TypeError('fn must be a function');
}
const onBefore = typeof before === 'function' ? before : () => {};
const onAfter = typeof after === 'function' ? after : () => {};
return new Proxy(fn, {
apply(target, thisArg, args) {
onBefore(args);
const result = target(...args);
onAfter(result);
return result;
},
construct(target, args) {
onBefore(args);
const result = target(...args);
onAfter(result);
return result;
},
});
}
module.exports = { wrapCallable };