Skip to content

Instantly share code, notes, and snippets.

@davidlacarta davidlacarta/safe.js
Created Jun 12, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.