Last active
April 28, 2022 09:13
-
-
Save iShawnWang/22a05e2afe5a741137ac7c513d21773b to your computer and use it in GitHub Desktop.
ES6 Proxy Optional Chain
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
const optional = (srcObj) => { | |
return new Proxy(() => {}, { | |
apply: () => { | |
return srcObj | |
}, | |
get: (__, prop) => { | |
if (srcObj && srcObj.hasOwnProperty(prop)) { | |
return optional(srcObj[prop]) | |
} else { | |
return optional(undefined) | |
} | |
}, | |
}) | |
} | |
const obj = { | |
a: 1, | |
b: { c: 'c', d: null }, | |
} | |
console.log(optional(obj)()) | |
console.log(optional(obj).b.c()) | |
console.log(optional(obj).b.d()) | |
console.log(optional(obj).b.d.e()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment