Order Validator With Rule Dependencies
Build an OrderValidator that checks orders against a changing set of rules. An order is { items: [{ name, price }, ...] }.
A rule is one of:
{ type: "prohibited", items: [names] }fails when the order contains any listed item.{ type: "price", min, max }fails when any item's price is belowminor abovemax.
Operations
addRule(name, rule)registers a rule. Returnfalseif the name is taken.addDependency(prerequisite, rule)declares thatruleis only meaningful onceprerequisitehas passed. Returnfalse, changing nothing, if either name is unknown, the two are the same, the dependency already exists, or it would create a cycle.removeRule(name)deletes a rule; returnfalseif it does not exist. So that no ordering is lost, every prerequisite of the removed rule becomes a prerequisite of every rule that depended on it.validate(order)evaluates the rules. A rule is skipped when any of its prerequisites failed or was skipped; otherwise it runs and passes or fails. Return{ valid, failed, skipped }:failedandskippedlist rule names in the order the rules were added, andvalidistruewhen both are empty.
addRule("no-weapons", { type: "prohibited", items: ["knife"] })
addRule("price-range", { type: "price", min: 1, max: 500 })
addDependency("no-weapons", "price-range")
validate({ items: [{ name: "knife", price: 9000 }] })
-> { valid: false, failed: ["no-weapons"], skipped: ["price-range"] }The round is AI-assisted and grades your tests as much as the code: after implementing, write a case for each branch.
Hints
Hint 1
Store each rule once, with two sets: the rules it depends on and the rules that depend on it. Keeping both directions makes removal local.
Hint 2
A new edge prerequisite -> rule closes a cycle exactly when prerequisite is already reachable from rule. One depth-first search over dependents answers that.
Hint 3
For validate, compute each rule's status from its prerequisites' statuses with memoised recursion; the DAG guarantees it terminates.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.