javascript / expert
Snippet
Subclassing Array with Proxy Interceptors for Guarded Array Mutations
Extending built-in Array while wrapping the instance in a JavaScript Proxy constructor trap allows intercepting dynamic index assignments, array methods (like push/unshift), and mutation traps while preserving native Array inheritance and behavior.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class GuardedArray extends Array {constructor(validator, ...items) {super(...items);return new Proxy(this, {set(target, prop, value, receiver) {if (typeof prop === 'string' && !isNaN(Number(prop))) {if (!validator(value)) {throw new TypeError(`Invalid value element '${value}' assigned at index ${prop}`);}}return Reflect.set(target, prop, value, receiver);}});}}const numbersOnly = new GuardedArray((val) => typeof val === 'number', 10, 20);numbersOnly.push(30);
nodejs
Breakdown
1
class GuardedArray extends Array {
Extends the JavaScript native Array constructor to subclass built-in array behaviors.
2
return new Proxy(this, {
Returns a transparent Proxy wrapper directly from the class constructor overriding the default instance return.
3
if (typeof prop === 'string' && !isNaN(Number(prop))) {
Checks whether the intercepted object property access corresponds to an array numeric index write.
4
return Reflect.set(target, prop, value, receiver);
Forwards validated property mutation calls to the internal target using Reflect meta-programming APIs.