Skip to content

Instantly share code, notes, and snippets.

@digitalconceptvisuals
Last active July 31, 2020 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digitalconceptvisuals/c468083ac52c48129e959d74c0ac650f to your computer and use it in GitHub Desktop.
Save digitalconceptvisuals/c468083ac52c48129e959d74c0ac650f to your computer and use it in GitHub Desktop.
// 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