Skip to content

Instantly share code, notes, and snippets.

@davidlacarta
Created June 12, 2018 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidlacarta/08ef40ae8c63efcd7895ab77b0c5a7dc to your computer and use it in GitHub Desktop.
Save davidlacarta/08ef40ae8c63efcd7895ab77b0c5a7dc to your computer and use it in GitHub Desktop.
const isObject = obj => obj && typeof obj === 'object';
const hasKey = (obj, key) => key in obj;
const safe = obj =>
new Proxy(obj, {
get: (target, name) => {
if (!hasKey(target, name)) {
return 'undefined';
}
if (!isObject(target[name])) {
return target[name];
}
return safe(target[name]);
}
});
const test = { a: { b: 'x' } };
const testSafe = safe(test);
// console.log(test.a.b); // x
console.log(testSafe.a.b); // x
// console.log(test.c.d); // TypeError
console.log(testSafe.c.d); // undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment