Write a basic `validate(schema, data)` that checks if data matches the schema. Support types: "string", "number", "boolean", "object" (with properties), "array".
Problem Statement
Write a basic `validate(schema, data)` that checks if data matches the schema. Support types: "string", "number", "boolean", "object" (with properties), "array".
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Check the schema type against typeof data.
š” Hint 2:
For "object" type, recursively validate each property in schema.properties.
š” Hint 3:
Handle nested objects by recursing. Handle required fields.
ā
Solution:
```javascript
function validate(schema, data) {
const errors = [];
function check(s, d, path) {
if (s.type === "object") {
if (typeof d !== "object" || d === null) { errors.push(`${path}: expected object`); return; }
if (s.properties) {
for (const key in s.properties) {
check(s.properties[key], d[key], `${path}.${key}`);
}
}
} else if (s.type === "array") {
if (!Array.isArray(d)) errors.push(`${path}: expected array`);
} else if (typeof d !== s.type) {
errors.push(`${path}: expected ${s.type}, got ${typeof d}`);
}
}
check(schema, data, "root");
return { valid: errors.length === 0, errors };
}
```