Last active
April 18, 2018 18:27
-
-
Save fpg1503/9c593cd498796e60b525816553bfe190 to your computer and use it in GitHub Desktop.
Safe 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
Object.prototype.toSafeProxy = function() { | |
const getter = (target, name, receiver) => { | |
const value = target[name] | |
if (value == null) { | |
return nullProxy(value) | |
} else if (typeof value === 'object') { | |
return value.toSafeProxy() | |
} else if (typeof value === 'function') { | |
return value | |
} else { | |
return primitiveProxy(value) | |
} | |
} | |
const nullProxy = (value) => { | |
return new Proxy({ | |
value: () => value, | |
fallbackTo: fallback => fallback, | |
flatMap: () => value | |
}, { get: getter }) | |
} | |
const primitiveProxy = (value) => { | |
return new Proxy({ | |
value: () => value, | |
fallbackTo: () => value, | |
flatMap: map => map(value) | |
}, { get: getter }) | |
} | |
return new Proxy(Object.assign({}, this, { | |
fallbackTo: () => this, | |
flatMap: map => map(this) | |
}), { | |
get: getter | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added
flatMap
to the safe proxies