Transfer practice · safeStock(item) returns zero for a missing record or absent quantity, and clamps a negative quantity to zero. It does not cap positive stock at one.
v3 · Activity 1 of 1 · missing-data · guards · validation · 12 min Runs here
Use a familiar idea in a different task. Read the changed requirement before running.
safeStock(item) returns zero for a missing record or absent quantity, and clamps a negative quantity to zero. It does not cap positive stock at one.
Interface: progress(quest:{done:number?,total:number?}?) -> number
| Input | Expected |
|---|---|
Missing itemnil | 0 |
Negative stock{ quantity = -3 } | 0 |
Positive stock{ quantity = 14 } | 14 |
local function progress(quest)
if quest == nil then return 0 end
local total = quest.total or 0
if total <= 0 then return 0 end
local done = quest.done or 0
return math.min(1, math.max(0, done / total))
end
return progressThe record guard precedes field access. The total guard prevents dividing by zero, then clamps the ratio.
New syntax: /, guard clauses
Reading quest.done when quest is nil fails before a fallback on the field can help. Check the outer record first.
Define policies explicitly: a missing quest or nonpositive total gives 0 progress; missing done means 0. Valid progress is clamped from 0 to 1.
math.max and math.min select numeric limits. They do not replace type validation for arbitrary remote input; this activity supplies numeric fields or nil.
Select a word or symbol in this authored example. Your editor draft stays unchanged.
progressquest
quest 0
total quest.total 0
total 0 0
done quest.done 0
math.min1, math.max0, done total
progressThis is a private experiment copy. It does not replace your answer or complete the activity.
These inputs apply when your scratchpad returns the function described by the activity interface.
Your output will appear here.
Replace this code with the starter? Download your draft to keep a copy.
Your output will appear here.
Sign in with RoCreators to save private progress across devices. Community verification is separate.