Explorer
Node.js

Create a function `createValidatedObject(schema)` that returns a Proxy which validates property assignments against the schema types.

Problem Statement

Create a function `createValidatedObject(schema)` that returns a Proxy which validates property assignments against the schema types.

Complexity

Time Complexity: -

Space Complexity: -

Hints

šŸ’” Hint 1: Proxy intercepts operations on an object (get, set, etc.). šŸ’” Hint 2: Use the set trap to validate the type before allowing assignment. šŸ’” Hint 3: Check typeof value against schema[prop] in the set handler. āœ… Solution: ```javascript function createValidatedObject(schema) { return new Proxy({}, { set(target, prop, value) { if (schema[prop] && typeof value !== schema[prop]) { throw new TypeError(`${prop} must be ${schema[prop]}`); } target[prop] = value; return true; } }); } ```

Proxy for Validation

Medium
Create a function `createValidatedObject(schema)` that returns a Proxy which validates property assignments against the schema types.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"name":"Alice","age":30,"err":"age must be number"}