function createValidatedProperty(obj, propName, validator) {
let value;
Object.defineProperty(obj, propName, {
get() {
return value;
},
set(newValue) {
if (!validator(newValue)) {
throw new Error(`Invalid value for ${propName}`);
}
value = newValue;
},
enumerable: true,
configurable: false
});
};
This function implements the validated property pattern: 1) It creates properties with custom validation logic, 2) It uses closures to store the property value privately, 3) The validator function determines if new values are acceptable, 4) It throws errors for invalid values, preventing data corruption, 5) The property appears normal from the outside but enforces business rules, 6) By making it non-configurable, the validation can't be removed, 7) This pattern is useful for creating objects with self-validating properties, ensuring data integrity throughout the application.