Skip to content

Instantly share code, notes, and snippets.

@saintsGrad15
Last active January 13, 2024 03:24
Show Gist options
  • Save saintsGrad15/63ed99967fac3c1c1435947360586df0 to your computer and use it in GitHub Desktop.
Save saintsGrad15/63ed99967fac3c1c1435947360586df0 to your computer and use it in GitHub Desktop.
Returns a flat proxied object wherein function values serve as computed properties and are called with the object as the value of this upon access.
const object = getDependentObject({
name: "john",
age: 39,
yearsTil40() { return 40 - this.age; }
});
console.log(object.yearsTil40); // 40 - 39 = 1
object.age = 30
console.log(object.yearsTil40); // 40 - 30 = 10
function getDependentObject(o) {
return new Proxy(o, {
get(target, property, receiver) {
if (typeof target[property] === "function") {
return target[property]?.call(receiver);
}
return target[property];
},
set(target, property, value) {
if (typeof target[property] === "function") {
throw new TypeError(`The "${property}" property is computed. Its value cannot be set directly.`);
}
else {
Reflect.set(target, property, value);
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment