From e5d4d3170d4de9fb520197fc7e4f259fd098979d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Borys=20=C5=BBmuda?= Date: Sat, 28 Sep 2024 10:00:48 +0200 Subject: [PATCH] feat: Added `Set::union()` method --- src/JavaScript/Set.php | 13 +++++++++++++ tests/Unit/SetTest.php | 29 +++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/JavaScript/Set.php b/src/JavaScript/Set.php index 653b6c0..dec721c 100644 --- a/src/JavaScript/Set.php +++ b/src/JavaScript/Set.php @@ -180,6 +180,19 @@ public function toArray(): array return $this->items; } + /** + * Merge the Set with the given Set. + * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/union + * + * @param \Rudashi\JavaScript\Set $other + * + * @return \Rudashi\JavaScript\Set + */ + public function union(Set $other): Set + { + return new Set([...$this->items, ...$other->items]); + } + /** * Returns Set values as SetIterator. * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/values diff --git a/tests/Unit/SetTest.php b/tests/Unit/SetTest.php index c43cc43..a88d911 100644 --- a/tests/Unit/SetTest.php +++ b/tests/Unit/SetTest.php @@ -435,6 +435,35 @@ }); }); +describe('union', function () { + test('merge values', function () { + $odds = new Set([1, 3, 5, 7, 9]); + $squares = new Set([1, 4, 9]); + + expect($odds->union($squares)) + ->toBeInstanceOf(Set::class) + ->toMatchArray([1, 3, 5, 7, 9, 4]); + }); + + test('`a` plus `b`', function () { + $a = new Set([1, 2, 3, 4]); + $b = new Set([5, 4, 3, 2]); + + expect($a->union($b)) + ->toBeInstanceOf(Set::class) + ->toMatchArray([1, 2, 3, 4, 5]); + }); + + test('`b` plus `a`', function () { + $a = new Set([1, 2, 3, 4]); + $b = new Set([5, 4, 3, 2]); + + expect($b->union($a)) + ->toBeInstanceOf(Set::class) + ->toMatchArray([5, 4, 3, 2, 1]); + }); +}); + describe('values', function () { it('returns new SetIterator', function () { $set = new Set(['foo', 'bar']);