Skip to content

Commit 7a901ef

Browse files
committed
add spec.list
1 parent 6b34f10 commit 7a901ef

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

spec.lua

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,12 @@ end
121121
---@param spec fun(value: any): boolean
122122
---@return fun(value: any): boolean
123123
function M.optional(spec)
124+
if type(spec) ~= "function" then
125+
M.fn.error(
126+
string.format("spec.lua: Spec '%s' must be a function (e.g. spec.keys for tables)", M.fn.pretty_print(spec))
127+
)
128+
end
129+
124130
return function(value)
125131
-- if no value is specified return true!
126132
if value == nil then
@@ -130,6 +136,31 @@ function M.optional(spec)
130136
end
131137
end
132138

139+
---Tests if the value is a list of `spec`
140+
---@param spec fun(value: any): boolean
141+
---@return fun(value: any): boolean
142+
function M.list(spec)
143+
if type(spec) ~= "function" then
144+
M.fn.error(
145+
string.format("spec.lua: Spec '%s' must be a function (e.g. spec.keys for tables)", M.fn.pretty_print(spec))
146+
)
147+
end
148+
149+
return function(value)
150+
if type(value) ~= "table" then
151+
return false
152+
end
153+
154+
for _, item in ipairs(value) do
155+
if not spec(item) then
156+
return false
157+
end
158+
end
159+
160+
return true
161+
end
162+
end
163+
133164
---Tests if all of predicates are valid
134165
---@param ... fun(value: any): boolean
135166
---@return fun(value: any): boolean

spec_test.lua

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,13 @@ describe("spec.lua", function()
5050
assert.False(spec.optional(spec.string)(false))
5151
end)
5252

53+
it("spec.list", function()
54+
assert.True(spec.list(spec.number) { 1, 2, 3, 4, 5, 6 })
55+
assert.False(spec.list(spec.number) { 1, 2, 3, 4, "Test", 6 })
56+
assert.False(spec.list(spec.number)(nil))
57+
assert.False(spec.list(spec.number) "Test")
58+
end)
59+
5360
it("spec.all_of", function()
5461
assert.False(spec.valid(spec.all_of(spec.string, spec.number), nil))
5562
assert.True(spec.valid(spec.all_of(spec.table, spec.some), { 1, 2 }))

0 commit comments

Comments
 (0)