Created
October 17, 2022 19:42
-
-
Save reaktivo/b698cc2bc60f81c5551536a69b75843e to your computer and use it in GitHub Desktop.
Intercept property access recursively in javascript
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
function intercept<T extends {}>( | |
obj: T, | |
callback: (path: string) => void, | |
path: string[] = [] | |
): T { | |
function isPlainObject(obj: unknown) { | |
return Object.prototype.toString.call(obj) === '[object Object]'; | |
} | |
const proxy = new Proxy(obj, { | |
get(target, property) { | |
if (Array.isArray(target[property]) || isPlainObject(target[property])) { | |
if (Array.isArray(target)) { | |
return intercept(target[property], callback, [ | |
...path.slice(0, -1), | |
path.at(-1) + '[*]', | |
]); | |
} | |
return intercept(target[property], callback, [ | |
...path, | |
String(property), | |
]); | |
} | |
if (target?.hasOwnProperty(property) && !Array.isArray(target)) { | |
callback([...path, String(property)].join('.')); | |
} | |
return target[property]; | |
}, | |
}); | |
return proxy; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment