Skip to content

Commit

Permalink
Added new match routine that works like a switch
Browse files Browse the repository at this point in the history
  • Loading branch information
tredfern committed Feb 20, 2022
1 parent 41a44c0 commit 418092d
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
17 changes: 17 additions & 0 deletions moonpie/utility/match.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
-- Copyright (c) 2022 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT

return function(value, matchTable)
if matchTable[value] then
if type(matchTable[value]) == "function" then
return matchTable[value]()
end

return matchTable[value]
end

-- Return default
return matchTable._
end
38 changes: 38 additions & 0 deletions moonpie/utility/match_spec.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
-- Copyright (c) 2022 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT

describe("moonpie.utility.match", function()
local match = require "moonpie.utility.match"

it("takes a value and returns the matching value from the table", function()
local value = "B"
local out = match(value, {
A = 1,
B = 2,
C = 3,
})

assert.equals(2, out)
end)

it("if the matching value is a function it returns the result from the function", function()
local value = "C"
local out = match(value, {
A = function() return 1 end,
B = function() return 2 end,
C = function() return 3 end,
})

assert.equals(3, out)
end)

it("can have a default result if nothing matches", function()
local out = match("D", {
A = 1, B = 2, C = 3, _ = 10
})

assert.equals(10, out)
end)
end)

0 comments on commit 418092d

Please sign in to comment.