-
-
Save digitalconceptvisuals/c468083ac52c48129e959d74c0ac650f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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