Skip to content

Instantly share code, notes, and snippets.

@instantiator
Last active July 14, 2023 15:28
Show Gist options
  • Save instantiator/276f10b1c5027b4b4d3a2923e50cc8e7 to your computer and use it in GitHub Desktop.
Save instantiator/276f10b1c5027b4b4d3a2923e50cc8e7 to your computer and use it in GitHub Desktop.
An experimental javascript Proxy object that reports the path that was requested (some limitations)
/** An experimental Proxy that reports the path that was requested */
class PathProxy {
constructor(id) {
let proxy = new Proxy({ identity: id }, {
get: (target, name) => {
if (name.toString() === 'identity') {
return target.identity;
} else {
if (!(name in target)) {
target[name] = new PathProxy(`${target.identity}.${name.toString()}`);
}
return target[name];
}
}
});
return proxy;
}
}
var reporter = new PathProxy('$');
console.log(reporter.test.a.path); // expected: { identity: '$.test.a.path' }
console.log(reporter.test.a.path.identity); // expected: $.test.a.path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment