Created
June 21, 2022 10:17
-
-
Save Rowadz/84159c48401e3ee5106e0f3ff492fa7c to your computer and use it in GitHub Desktop.
An infinite proxy object that will never return undefined
This file contains 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
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) |
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())
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
Callable magic