Implement a small validate(value, schema) helper for checking simple runtime data.
The function should return:
{ valid: boolean, errors: string[] }
1. Primitive Schemas
A schema can be a string shorthand:
validate('Ada', 'string');
validate(42, 'number');
validate(true, 'boolean');
Supported primitive types:
'string''number''boolean'
2. Object Schemas
Object schemas use type, properties, and optional required fields:
const userSchema = {
type: 'object',
required: ['id', 'name'],
properties: {
id: 'number',
name: 'string'
}
};
Rules:
- The value must be a plain object
- Arrays and
null are not valid objects - Required properties must exist and cannot be
undefined - Optional properties are validated only when present
- Collect all top-level property errors instead of stopping at the first one
Examples
validate({ id: 1, name: 'Ada' }, userSchema);
// { valid: true, errors: [] }
validate({ id: '1' }, userSchema);
// { valid: false, errors: ['$.id should be number', '$.name is required'] }
This problem intentionally focuses on a compact top-level object contract. Keep the behavior small, deterministic, and easy to test.