Skip to content

Instantly share code, notes, and snippets.

@DadgadCafe
Created March 24, 2017 05:29
Show Gist options
  • Save DadgadCafe/143248f7049909d1259c7aa40ba552c8 to your computer and use it in GitHub Desktop.
Save DadgadCafe/143248f7049909d1259c7aa40ba552c8 to your computer and use it in GitHub Desktop.
it works like obj?.prop?.name to prevent reference error, using Proxy.
'use strict'
const isObject = obj => typeof obj === 'object'
const hasKey = (obj, key) => key in obj
const Undefined = new Proxy({},{
get (target, key, receiver) {
// always return Undefined when accessing Undefined.whatever
return receiver
}
})
// fallback to right value
const either = (left, right) => left === Undefined ? right : left
const makeSafe = obj =>
new Proxy(obj, {
get (target, key) {
return hasKey(target, key)
? isObject(target[key])
? makeSafe(target[key])
: target[key]
: Undefined
}
})
const safeO = makeSafe({
innerO: {
a: 1
}
})
safeO.innerO.a //1
safeO.name // Undefined
safeO.innerO.name // Undefined, no error occured
either(safeO.innerO.name, 'not found') // fall back to 'not found'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment