Build a Validation Schema Builder

Write the code, see it run, pass the checks.

The problem

  • hard
  • Code
  • Pro

Write four functions that build schemas: string(), number(), object(shape), where shape maps keys to schemas, and array(item), where item is the schema for every element. Every schema has parse(value), returning { ok: true, value: parsed } or { ok: false, errors }, where errors lists { path, message } in the order found: path joins the keys and indexes from the top with dots, such as "tags.1" or "address.city", and is "" for the value itself. The messages are "Expected string", "Expected number" (NaN isn't one), "Expected object" (null and arrays aren't), "Expected array", and for the rules below "Must be at least N characters" and "Expected integer". A value of the wrong type gets only that error. Object and array values parse into new ones, and objects keep only the keys in shape. Rules: string has min(n), for at least n characters, and number has int(). Every schema has optional(), after which undefined passes; an optional key that's missing is left out of the parsed object. Each rule returns a new schema and leaves the one it was called on unchanged.

Your code must pass

  • Parses strings and numbers
  • Applies min and int rules
  • Each rule returns a new schema
  • Validates objects and arrays with paths to each error
  • Keeps only the keys an object schema lists
  • Allows missing values only when optional