Created
March 24, 2017 05:29
-
-
Save DadgadCafe/143248f7049909d1259c7aa40ba552c8 to your computer and use it in GitHub Desktop.
it works like obj?.prop?.name to prevent reference error, using Proxy.
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
'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