Skip to content

Instantly share code, notes, and snippets.

@Rowadz
Created June 21, 2022 10:17
Show Gist options
  • Save Rowadz/84159c48401e3ee5106e0f3ff492fa7c to your computer and use it in GitHub Desktop.
Save Rowadz/84159c48401e3ee5106e0f3ff492fa7c to your computer and use it in GitHub Desktop.
An infinite proxy object that will never return undefined
const magicObject = new Proxy(
{},
{
get(_, prop) {
return new Proxy({ [prop]: 'hmmm?' }, this)
},
}
)
console.log(magicObject.what)
console.log(magicObject.what.what)
console.log(magicObject.what.what.what)
console.log(magicObject.what.what.what.what)
console.log(magicObject.what.what.what.what.what)
@Rowadz
Copy link
Author

Rowadz commented Aug 21, 2022

Callable magic

const magicObject = new Proxy(function Magic() {}, {
  get(_target, prop, _receiver) {
    return new Proxy(function Magic() {}, this)
  },
  apply(fun, _thisArg, _argsList) {
    return new Proxy(function Magic() {}, this)
  },
})

console.log(magicObject.what)
console.log(magicObject.dasdas().das().adsasd.fadsfds().fasdfsad)
console.log(magicObject.what.what().what)
console.log(magicObject.what.what.what.what)
console.log(magicObject.what.what.what.what.what)

@Rowadz
Copy link
Author

Rowadz commented Aug 21, 2022

Dynamic getters

const magicObject = new Proxy(
  {
    dict: { id: 1, age: 2423, name: 'rowadz' },
  },
  {
    get(target, prop) {
      const key = prop.replace('get', '').toLowerCase()
      return () => target.dict[key]
    },
  }
)

console.log(magicObject.getId())
console.log(magicObject.getAge())
console.log(magicObject.getName())

@Rowadz
Copy link
Author

Rowadz commented Aug 21, 2022

python example:

from posixpath import split


class MagicClass(object):
    _dict = {
        'id': 1,
        'name': 'rowadz',
        'age': 789
    }

    def __getattr__(self, name):
        def wrapper(*args, **kwargs):
            _, key = name.split('_')
            return self._dict[key]
        return wrapper

ob = MagicClass()

print(ob.get_id())
print(ob.get_name())
print(ob.get_age())

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