javascript / expert
Snippet
Reactive Array Subclasses Using Proxy Traps and Symbol.species
Subclassing Array in JavaScript requires precise management of method species and proxy traps. Symbol.species ensures built-in array methods like slice or map return standard Array instances rather than subclass instances, preventing unintended handler leaks. Encapsulating the subclass within a Proxy intercepts element access and mutation transparently.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class ObservableArray extends Array {static get [Symbol.species]() {return Array;}static create(onMutation, ...items) {const instance = new ObservableArray(...items);return new Proxy(instance, {set(target, prop, value, receiver) {const res = Reflect.set(target, prop, value, receiver);if (typeof prop !== 'symbol' && !isNaN(Number(prop))) {onMutation({ type: 'set', index: Number(prop), value });}return res;}});}}const list = ObservableArray.create(m => console.log('Mutated:', m), 'a', 'b');const sub = list.slice(0, 1);list[2] = 'c';
nodejs
Breakdown
1
static get [Symbol.species]() { return Array; }
Overrides the species accessor so derived array operations return base Array instances.
2
return new Proxy(instance, {
Wraps the customized array instance in a Proxy handler for intercepting internal traps.
3
set(target, prop, value, receiver) {
Traps property assignments to track numeric index modifications and trigger mutation hooks.