Skip to content

Instantly share code, notes, and snippets.

@ger86
Created July 22, 2020 11:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ger86/b9ce62aef80b7ddb95dc5adc8c81c22f to your computer and use it in GitHub Desktop.
Save ger86/b9ce62aef80b7ddb95dc5adc8c81c22f to your computer and use it in GitHub Desktop.
/************************************************************
*
* 💪🏼💪🏼💪🏼 Javascript Proxy 💪🏼💪🏼💪🏼
*
************************************************************/
// 1️⃣ Performing an action when accesing a property
const person = { name: "Gerardo", email: "gerardo@latteandcode.com" };
const personProxy = new Proxy(person, {
get: function (item, property, itemProxy) {
console.log(`'${property}' property has been acccesed`);
return item[property];
},
});
personProxy.name; // "'name' property has been acccesed"
// 2️⃣ Performing an action when setting the value of a property
const person = { name: "Gerardo", email: "gerardo@latteandcode.com" };
const personProxySetter = new Proxy(person, {
set: function (item, property, value, itemProxy) {
console.log(`'${property}' property has been set`);
item[property] = value; // 🆒
},
});
personProxySetter.name = 'Gerardo Fernández'; // "'name' property has been set"
// 3️⃣ Private properties
const person = { name: "Gerardo", _email: "gerardo@latteandcode.com" };
const personWithPrivateProperties = new Proxy(person, {
has: (obj, prop) => {
if (typeof prop === "string" && prop.startsWith("_")) {
return false;
}
return prop in obj;
},
ownKeys: (obj) => {
return Reflect.ownKeys(obj).filter(
(prop) => typeof prop !== "string" || !prop.startsWith("_")
);
},
get: (obj, prop) => {
if (typeof prop === "string" && prop.startsWith("_")) {
return undefined;
}
return obj[prop];
},
});
console.log(personWithPrivateProperties._email); // undefined
for (let property in personWithPrivateProperties) {
console.log(property); // Only 'name'
}
// 4️⃣ Validating data
const person = { name: "Gerardo", age: 33 };
const personValidator = new Proxy(
person,
{
set(item, property, value) {
if (property === "age") {
if (!Number.isInteger(value) || value < 0 || value > 110) {
throw new TypeError("Invalid age");
}
}
item[property] = value;
},
}
);
personValidator.age = "33"; // Type Error: invalid age
// 5️⃣ Negative index for arrays
const array = ["foo", "bar", "zeta"];
const arrayWithNegativeIndex = new Proxy(array, {
get: function (target, propKey) {
const propKeyNumber = Number(propKey);
if (Number.isInteger(propKeyNumber) && propKeyNumber < 0) {
propKey = String(target.length + propKeyNumber);
}
return target[propKey];
},
});
console.log(arrayWithNegativeIndex[-2]); // 'bar'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment