Skip to content

Commit 0d8ef3a

Browse files
committed
add spec.optional
1 parent ded20d2 commit 0d8ef3a

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

spec.lua

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,18 @@ function M.exists(value)
6666
return value ~= nil
6767
end
6868

69+
---Tests if value is supplied that it matches the spec
70+
---@param spec fun(value: any): boolean
71+
---@return fun(value: any): boolean
72+
function M.optional(spec)
73+
return function(value)
74+
if value then
75+
return spec(value)
76+
end
77+
return true
78+
end
79+
end
80+
6981
---Tests if all of predicates are valid
7082
---@param ... fun(value: any): boolean
7183
---@return fun(value: any): boolean

spec_test.lua

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,12 @@ describe("spec.lua", function()
4343
assert.True(spec.exists "Test")
4444
end)
4545

46+
it("spec.optional", function()
47+
assert.True(spec.optional(spec.string) "Hello, World")
48+
assert.True(spec.optional(spec.string)(nil))
49+
assert.False(spec.optional(spec.string)(true))
50+
end)
51+
4652
it("spec.all_of", function()
4753
assert.False(spec.valid(spec.all_of(spec.string, spec.number), nil))
4854
assert.True(spec.valid(spec.all_of(spec.table, spec.some), { 1, 2 }))

0 commit comments

Comments
 (0)