Last active
June 27, 2021 19:28
-
-
Save gvergnaud/ee9640261ac1e17943a59a7da5ab61d1 to your computer and use it in GitHub Desktop.
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
// 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