Last active
February 17, 2020 12:55
-
-
Save iainjreid/4ea9fd166c76456a419a6afbf0d2f771 to your computer and use it in GitHub Desktop.
Property validation using a JavaScript Proxy
This file contains hidden or 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 shape = new Proxy({}, { | |
set: (obj, prop, value) => { | |
if (prop === 'sides') { | |
if (!(value > 0)) { | |
throw Error('Property "sides" must be greater than zero'); | |
} | |
} | |
// Set the value | |
obj[prop] = value; | |
// Return success | |
return true | |
} | |
}); | |
shape.sides = 4; // Works - 4 | |
shape.sides = 0; // Error - Property "sides" must be greater than zero |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment