3.1 KiB
id, title, challengeType, dashedName
| id | title | challengeType | dashedName |
|---|---|---|---|
| 6a0dcc730cb92a616f86f0c2 | Challenge 298: Schema Validator Part 4 | 28 | challenge-298 |
--description--
Given an object (JavaScript) or dictionary (Python), determine if it matches the following schema:
Roles = "user" | "creator" | "moderator" | "staff" | "admin"
{
username: string,
posts: number,
verified: boolean,
role: Roles,
supporter?: boolean
}
- The pipe (
|) symbol means "or".rolemust be one of the listedRolesvalues. - The question mark (
?) aftersupportermeans that the field is optional, but is the specified type if it exists. - Extra keys are allowed
--hints--
isValidSchema({ username: "vivian", posts: 1, verified: false, role: "user", supporter: true }) should return true.
assert.isTrue(isValidSchema({ username: "vivian", posts: 1, verified: false, role: "user", supporter: true }));
isValidSchema({ username: "rudolph", posts: 15, verified: true, role: "creator" }) should return true.
assert.isTrue(isValidSchema({ username: "rudolph", posts: 15, verified: true, role: "creator" }));
isValidSchema({ username: "hernandez", posts: 35, verified: true, role: "moderator", supporter: false, followers: 55 }) should return true.
assert.isTrue(isValidSchema({ username: "hernandez", posts: 35, verified: true, role: "moderator", supporter: false, followers: 55 }));
isValidSchema({ username: "julia", posts: 50, verified: true, role: "admin", supporter: "true" }) should return false.
assert.isFalse(isValidSchema({ username: "julia", posts: 50, verified: true, role: "admin", supporter: "true" }));
isValidSchema({ username: "bernard", posts: 0, verified: true, role: "friend", supporter: true }) should return false.
assert.isFalse(isValidSchema({ username: "bernard", posts: 0, verified: true, role: "friend", supporter: true }));
isValidSchema({ username: "felix", posts: 40, verified: "yes", role: "staff", supporter: false }) should return false.
assert.isFalse(isValidSchema({ username: "felix", posts: 40, verified: "yes", role: "staff", supporter: false }));
isValidSchema({ username: "jimmy", posts: true, verified: false, role: "creator", supporter: true }) should return false.
assert.isFalse(isValidSchema({ username: "jimmy", posts: true, verified: false, role: "creator", supporter: true }));
isValidSchema({ username: true, posts: 30, verified: true, role: "moderator", supporter: false }) should return false.
assert.isFalse(isValidSchema({ username: true, posts: 30, verified: true, role: "moderator", supporter: false }));
--seed--
--seed-contents--
function isValidSchema(obj) {
return obj;
}
--solutions--
function isValidSchema(obj) {
const roles = ["user", "creator", "moderator", "staff", "admin"];
return (
typeof obj.username === 'string' &&
typeof obj.posts === 'number' &&
typeof obj.verified === 'boolean' &&
roles.includes(obj.role) &&
(obj.supporter === undefined || typeof obj.supporter === 'boolean')
);
}