-
-
Save mmfilesi/48270df221afcb6ef43f35be91492842 to your computer and use it in GitHub Desktop.
propiedades profundas seguras
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
/* 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