Level: Senior
Education: Masters
Years of Experience: 10
Questions Asked:
Write a function to validate a data structure that represents the reporting hierarchy of an organization. Here’s an example:
const employees = [
{ name: ‘alice’,
title: “ceo”,
salary: 100,
reports: [{
name: “bob”,
title: “cfo”,
salary: 10,
reports: [{
name: ‘zorp’,
title:“controller”,
salary: 40
}],
}],
}]
At the top level, we have a list of employees with various properties. Note the reports property in particular. An employee can have properties that are also lists of employees.
Validation rules
whether or not a data structure is valid depends on a schema describing a valid employee. Here is an example of a Schema.
const schema = {
employee: [
{
name: “name”,
required: true,
type: “string”
},
{
name: “title”,
required: true,
type: “string”
},
{
name: “salary”,
required: false,
type: “number”
},
{
name: “remote”,
required: false,
type: “boolean”
},
{
name: “reports”,
required: false,
type: “array:employee”
},
]
}
If the entire data structure conforms to the schema, return{ ok: true, message: “success” }
if a required property doesn’t exist on the validation, you should return{ ok: false, message: “${name} does not exist” }
if a property type is invalid, you should return { ok: false, message: “${name} property invalid ${type}” }
if a property does not belong, you should return { ok: false, message: “property ${prop} does not belong” } .
You can return the first error you find and ignore any other errors.
complete the validate function below.
function validate(employees, schema) {
}