Skip to content

Instantly share code, notes, and snippets.

@digitalconceptvisuals
Last active Jul 31, 2020
Embed
What would you like to do?
// Array proxy
const PureArray = (...args) =>
new Proxy([...args], // Create internal array
// Handler with traps
{
// Intercept assignment to array using index
set(target, property, value, receiver) {
// Allow built in properties like length
if (Reflect.has(target, property))
return Reflect.get(target, property, receiver);
// Check if property is positive integer
const index = Number.parseInt(property);
if (Number.isNaN(index) || index < 0)
throw new Error("Index must be >= 0");
// Otherwise call the internal array
return Reflect.set(target, property, value, receiver);
},
// Intercept access to the array via index
get(target, property, receiver) {
// Check if its one of the built in properties
if (Reflect.has(target, property))
return Reflect.get(target, property, receiver);
// Check if property is positive integer
const index = Number.parseInt(property);
if (Number.isNaN(index) || index < 0)
throw new Error("Index must be >= 0");
// Otherwise call the internal array
return Reflect.get(target, property, receiver);
}
}
);
// let's create our "Pure" array
const myArray = PureArray(1, 2, 3);
console.log(myArray);
// Normal operations work
myArray[3] = 4;
console.log(myArray);
console.log(myArray.slice(2, 3));
console.log(myArray.length);
// These don't work anymore
myArray[-1] = 5;
console.log(myArray[-3]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment