Skip to content

Instantly share code, notes, and snippets.

@mmfilesi
Created May 3, 2017 05:19
Show Gist options
  • Save mmfilesi/48270df221afcb6ef43f35be91492842 to your computer and use it in GitHub Desktop.
Save mmfilesi/48270df221afcb6ef43f35be91492842 to your computer and use it in GitHub Desktop.
propiedades profundas seguras
/* Acceder a propiedades de forma segura. Leído en El abismo de null
https://elabismodenull.wordpress.com/2017/03/16/pequenos-trucos-para-mejorar-tu-javascript/
*/
const isObject = obj => obj && typeof obj === 'object';
const hasKey = (obj, key) => key in obj;
const Undefined = new Proxy({}, {
get: function(target, name){
return Undefined;
}
});
function safe(obj) {
return new Proxy(obj, {
get: function(target, name) {
return hasKey(target, name) ?
(isObject(target[name]) ?
safe(target[name]) : target[name]) : Undefined;
}
});
}
const userSafe = safe(user);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment