Watch Nested Changes with a Proxy
Write the code, see it run, pass the checks.
The problem
- hard
- Code
- Pro
Write observe(target, onChange), for a target made of plain objects and arrays: return a Proxy that changes target and reports each change. After every property set through it, call onChange with { type: "set", path, value }, and after every delete, with { type: "delete", path }, where path is an array of the keys from the top, such as ["user", "name"]; array indexes arrive as strings, such as "2". Changes at any depth are reported: reading an object or array through the proxy gives a watched view of it, including objects assigned later. Array methods report each property they change, so push("c") on a two-item array reports one set at index 2. Setting a property to the value it already has, or deleting one that isn't there, changes nothing and reports nothing.
Your code must pass
- Reports top-level sets and deletes
- Reports nested changes with their path
- Reports changes made by array methods
- Watches objects added later
- Ignores changes that change nothing
- Changes the original object