Skip to content

Instantly share code, notes, and snippets.

@joelnet
Created August 20, 2019 17:11
Show Gist options
  • Save joelnet/8ea04f67f4fd84f7c6c8a2a05a49a996 to your computer and use it in GitHub Desktop.
Save joelnet/8ea04f67f4fd84f7c6c8a2a05a49a996 to your computer and use it in GitHub Desktop.
ES6 Proxy Set
/**
* Demo for https://twitter.com/joelnet/status/1163820524709076992
*/
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
// ✨✨✨ Wrap new Person in a Proxy ✨✨✨
const proxy = new Proxy(
new Person('C#', 'Joel'),
stringValidator('firstName', 'lastName')
)
// 👌 Everything is okay
proxy.firstName = 'JavaScript'
console.log(proxy)
// ⛔ Assignment has been rejected
proxy.lastName = null
/**
* Validates properties are non-empty string
*/
function stringValidator(...props) {
return ({
set(target, name, value) {
if (props.includes(name)) {
if (value == null || value == '') {
throw new TypeError(`${name} cannot be blank`)
}
if (typeof value !== 'string') {
throw new TypeError(`${name} does not support type "${typeof value}". Must be a "string".`)
}
}
target[name] = value
return true
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment