-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added new match routine that works like a switch
- Loading branch information
Showing
2 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |