Skip to content

Commit 9478734

Browse files
committed
feat(Set): add | operator for union
1 parent 3a9b379 commit 9478734

3 files changed

Lines changed: 31 additions & 2 deletions

File tree

spec/Set_spec.lua

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,15 @@ describe("mods.Set", function()
119119
end)
120120

121121
if runtime.version_num > 502 then
122+
it("__bor (|) returns set union", function()
123+
local a = Set({ "a", "b" })
124+
local b = Set({ "b", "x" })
125+
local u = assert(load("local x, y = ...; return x | y"))(a, b)
126+
assert.are_same({ a = true, b = true, x = true }, u)
127+
assert.are_same({ a = true, b = true }, a)
128+
assert.are_same({ b = true, x = true }, b)
129+
end)
130+
122131
it("__band (&) returns set intersection", function()
123132
local a = Set({ "a", "b", "c" })
124133
local b = Set({ "b", "x" })

src/mods/Set.lua

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ Set.values = tbl.keys
134134

135135
Set.__add = Set.union
136136
Set.__band = Set.intersection
137+
Set.__bor = Set.union
137138
Set.__bxor = Set.symmetric_difference
138139
Set.__eq = tbl.same
139140
Set.__le = Set.issubset

types/Set.lua

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
---@class mods.Set<T>:{[T]:true}
1717
---@operator add(mods.Set):mods.Set
1818
---@operator band(mods.Set):mods.Set
19+
---@operator bor(mods.Set):mods.Set
1920
---@operator bxor(mods.Set):mods.Set
2021
---@operator sub(mods.Set):mods.Set
2122
---@overload fun(t?:any[]|mods.Set|mods.List):mods.Set
@@ -213,8 +214,8 @@ function Set:symmetric_difference(set) end
213214
---
214215
---> [!NOTE]
215216
--->
216-
---> `union` is also available as the `__add` (`+`) operator.
217-
---> `a:union(b)` is equivalent to `a + b`.
217+
---> `union` is available as `__add` (`+`) and `__bor` (`|`) on Lua 5.3+.
218+
---> `a:union(b)` is equivalent to `a + b` and `a | b`.
218219
---
219220
---@param self mods.Set|table<any,true>
220221
---@param set mods.Set|table<any,true>
@@ -393,6 +394,24 @@ function Set:values() end
393394
---@return mods.Set
394395
function Set.__add(self, set) end
395396

397+
---
398+
---Return the union of two sets using `|`.
399+
---
400+
---```lua
401+
---a = Set({ "a", "b" })
402+
---b = Set({ "b", "c" })
403+
---u = a | b --> { a = true, b = true, c = true }
404+
---```
405+
---
406+
---> [!NOTE]
407+
--->
408+
---> `__bor` is the operator form of `:union(set)` on Lua 5.3+.
409+
---
410+
---@param self mods.Set|table<any,true>
411+
---@param set mods.Set|table<any,true>
412+
---@return mods.Set
413+
function Set.__bor(self, set) end
414+
396415
---
397416
---Return the intersection of two sets using `&`.
398417
---

0 commit comments

Comments
 (0)