Skip to content

Instantly share code, notes, and snippets.

@reaktivo
Created October 17, 2022 19:42
Show Gist options
  • Save reaktivo/b698cc2bc60f81c5551536a69b75843e to your computer and use it in GitHub Desktop.
Save reaktivo/b698cc2bc60f81c5551536a69b75843e to your computer and use it in GitHub Desktop.
Intercept property access recursively in javascript
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