Problem Statement
Implement a JavaScript Proxy that automatically increments a property’s value every time it is accessed.
When a property is read, the value should increase by 1 before being returned.
This behavior should only apply to existing numeric properties on the target object.
Example
let obj = { i: 0 };
const proxy = new Proxy(obj, {
get(target, property) {
if (target[property] !== undefined) {
target[property] += 1;
return target[property];
}
},
});
console.log(proxy.i); // 1
console.log(proxy.i); // 2
console.log(proxy.i); // 3
Explanation:
- The first access increments
ifrom0→1. - The second access increments
ifrom1→2. - The third access increments
ifrom2→3.
Constraints
- The Proxy should only increment existing numeric properties.
- Accessing a non-existent property should return
undefined. - The target object must reflect the updated value.
Expected Output
1
2
3