Skip to content

Instantly share code, notes, and snippets.

@fpg1503
Last active April 18, 2018 18:27
Show Gist options
  • Save fpg1503/9c593cd498796e60b525816553bfe190 to your computer and use it in GitHub Desktop.
Save fpg1503/9c593cd498796e60b525816553bfe190 to your computer and use it in GitHub Desktop.
Safe Proxy
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
})
}
@fpg1503
Copy link
Author

fpg1503 commented Apr 18, 2018

This is an attempt to recreate Swift's optional chaining and nil coalescing feature.
I don't like the fact that I have to access value() to fetch primitive values but it's a work in progress!

The current usage is the following:
someObject.toSafeProxy().aKey.anotherKey.somethingThatMayNotExist.fallbackTo('some fallback value')

@fpg1503
Copy link
Author

fpg1503 commented Apr 18, 2018

Added flatMap to the safe proxies

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment