Skip to content

Instantly share code, notes, and snippets.

@isthatcentered
Last active March 16, 2019 08:38
Show Gist options
  • Save isthatcentered/2b8385f9e7487acf757f193a7fb29578 to your computer and use it in GitHub Desktop.
Save isthatcentered/2b8385f9e7487acf757f193a7fb29578 to your computer and use it in GitHub Desktop.
Javascript ES6 proxy object that never fails
import { Yolo } from "./yolo"
import { Loggable } from "./loggable"
// Nothing in this object ? Don't care, yolo
const x = Yolo<any>().whatever.i.wont.fail.lolz().im.batman()
// I know it's boring but If the value exist you can still access it ;)
const Y = Yolo<any>( { hello: { name: "world" } } ).hello.name // -> "world"
// Also, yay typescript
const z = Yolo<BatFamily>().batman.robin.alfred.notPartOfTheInterface.I.wont.fail().though.lolz()
// go meta, use a proxy to log the proxy accesses
const LoggedYolo: <T>( target: T ) => T = target => Loggable( Yolo( target ) )
const w = Yolo<BatFamily>().batman.robin.alfred.you.get.the.idea // -> Accessed "Batman" -> Accessed "robin" -> Accessed "alfred" -> ...
// Not important
interface BatFamily
{
batman: {
robin: {
alfred: string
}
}
}
export function Loggable<T extends Object>( target: T ): T
{
return new Proxy( target, {
get( target, prop, receiver )
{
console.log( "Accessed", prop )
return Reflect.get( target, prop, receiver )
},
} )
}
// A whatever can be called or have it's property accessed
function Whatever(): any
{
return new Proxy( function () {
}, {
get( target, key )
{
if ( key === "name" )
return "Whatver" // console.log displays function.prototype.name and will fail without this
return Whatever()
},
apply()
{
console.log( "apply" )
return Whatever()
},
} )
}
function Yolo<T>( target: DeepPartial<T> | any = {} ): T
{
return new Proxy( target, {
get: ( target, key ) => {
const value = Reflect.get( target, key )
if ( !value )
return Whatever()
return (typeof value === "object") ?
Yolo( value ) :// We want to be able to safely travel further
value // if we have a primitive value, we won't be able to traverse further in typescript, no need to proxy it
},
apply()
{
return Whatever
},
} ) as T
}
type DeepPartial<T> = {[P in keyof T]?: DeepPartial<T[P]>}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment