Created
July 1, 2017 02:02
-
-
Save cbroberg/ae5324ff8b409ab16be1aceafd5503f5 to your computer and use it in GitHub Desktop.
Proxy Validator
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 rand = Math.random() < 0.5 | |
const throwError = rand // random boolean | |
// validation, error handling, boolean | |
let validator = { | |
set: function(obj, prop, value) { | |
if (prop === 'age') { | |
if (!Number.isInteger(value)) { | |
if (throwError) { | |
throw new TypeError('The age is not an integer') | |
} else { | |
log('Age must be a number') | |
} | |
} | |
if (value > 200) { | |
if (throwError) { | |
throw new RangeError('The age seems invalid') | |
} else { | |
log('Age must be a positive number') | |
} | |
} | |
} | |
// The default behavior to store the value | |
obj[prop] = value | |
// Indicate success | |
return true | |
} | |
} | |
let person = new Proxy({}, validator) | |
person.age = 100 | |
console.log(person.age) // 100 | |
person.age = 'young' // Throws an exception | |
person.age = 300 // Throws an exception |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment