Get/set proxy | class ExtendedArray extends Array {
constructor() {
super();
this.map = new Map();
}
set(index, value) {
this.map.set(index, value);
}
get(index) {
return this.map.get(index);
}
}
Object.defineProperty(ExtendedArray.prototype, 'value', {
set(index, value) {
this.set(index, value);
},
get() {
return {
[Symbol.toPrimitive](hint) {
if (hint === 'number') {
return this.get(this);
}
},
};
},
});
function testArrayReadWrite(loops) {
const arraySize = 1000000;
const testArray = new ExtendedArray(arraySize);
for (let i = 0; i < loops; i++) {
const index = i % arraySize;
testArray[index] = 42;
const value = testArray[index];
}
}
testArrayReadWrite(1000);
| ready |
ES6 Proxy | class ExtendedArray {
constructor() {
this.map = new Map();
return new Proxy(this, {
set: (target, prop, value) => {
if (!isNaN(prop)) {
target.map.set(Number(prop), value);
return true;
}
target[prop] = value;
return true;
},
get: (target, prop) => {
if (!isNaN(prop)) {
return target.map.get(Number(prop));
}
return target[prop];
}
});
}
}
function testArrayReadWrite(loops) {
const arraySize = 1000000;
const testArray = new ExtendedArray(arraySize);
for (let i = 0; i < loops; i++) {
const index = i % arraySize;
testArray[index] = 42;
const value = testArray[index];
}
}
testArrayReadWrite(1000);
| ready |