Skip to content

Instantly share code, notes, and snippets.

@iShawnWang
Last active April 28, 2022 09:13
Show Gist options
  • Save iShawnWang/22a05e2afe5a741137ac7c513d21773b to your computer and use it in GitHub Desktop.
Save iShawnWang/22a05e2afe5a741137ac7c513d21773b to your computer and use it in GitHub Desktop.
ES6 Proxy Optional Chain
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