javascript / expert
Snippet
Metaprogramming Function Invocations with Proxy Apply Traps
Functions in JavaScript are first-class objects that can be wrapped in a Proxy. By trapping the apply handler, you can intercept function execution for validation, telemetry, or argument transformation prior to invocation.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function createValidatedFunction(fn, validator) {return new Proxy(fn, {apply(target, thisArg, args) {if (!validator(...args)) {throw new TypeError('Invalid argument types provided to proxied function');}return Reflect.apply(target, thisArg, args);}});}const add = createValidatedFunction((a, b) => a + b,(a, b) => typeof a === 'number' && typeof b === 'number');
nodejs
Breakdown
1
return new Proxy(fn, {
Wraps the function target inside a Proxy instance.
2
apply(target, thisArg, args) {
Traps function calls, receiving target function, context, and passed arguments.
3
return Reflect.apply(target, thisArg, args);
Forwards execution to the target function using Reflect API after validation succeeds.