javascript / expert
Snippet
Metaprogramming Control Flow Interception with Proxy Traps
The Proxy apply trap intercepts function calls at runtime. Combined with Reflect.apply, it enables pre-execution validation gates and custom guard checks directly in the call stack without altering the underlying function source.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function createGuardedTarget(targetFunction, validator) {return new Proxy(targetFunction, {apply(target, thisArg, argumentsList) {const isValid = validator(...argumentsList);if (!isValid) {throw new RangeError('Function arguments failed validation check');}return Reflect.apply(target, thisArg, argumentsList);}});}const calculateTax = (amount, rate) => amount * rate;const safeCalculateTax = createGuardedTarget(calculateTax,(amount, rate) => typeof amount === 'number' && amount > 0 && rate > 0);console.log(safeCalculateTax(100, 0.2)); // 20
nodejs
Breakdown
1
apply(target, thisArg, argumentsList) {
Intercepts invocation execution requests directed at the target function.
2
throw new RangeError('Function arguments failed validation check');
Halts control flow execution before invoking target function if validation fails.
3
return Reflect.apply(target, thisArg, argumentsList);
Delegates valid calls to underlying target with original context bindings.