Last active
January 13, 2024 03:24
-
-
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.
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
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 |
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
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