Skip to content

Instantly share code, notes, and snippets.

@gvergnaud
Last active June 27, 2021 19:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gvergnaud/ee9640261ac1e17943a59a7da5ab61d1 to your computer and use it in GitHub Desktop.
Save gvergnaud/ee9640261ac1e17943a59a7da5ab61d1 to your computer and use it in GitHub Desktop.
// safe objects won't throw when trying to get a
// property which doesn't exist.
const safe = value => new Proxy({
extract() {
return value
}
}, {
get(obj, key) {
return key === 'extract'
? obj[key]
: safe(
value !== undefined && value !== null
? value[key]
: value
)
}
})
const user = {
name: 'Paul',
location: {
city: 'Paris'
},
friends: [
{
name: 'Patrick'
}
]
}
console.log(safe(user).name.extract())
// => Paul
console.log(safe(user).friends[0].name.length.extract())
// => 7
console.log(safe(user).friends[3].name.length.extract())
// => undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment