Skip to content

Instantly share code, notes, and snippets.

@cbroberg
Created July 1, 2017 02:02
Show Gist options
  • Save cbroberg/ae5324ff8b409ab16be1aceafd5503f5 to your computer and use it in GitHub Desktop.
Save cbroberg/ae5324ff8b409ab16be1aceafd5503f5 to your computer and use it in GitHub Desktop.
Proxy Validator
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