From dc62d25163c32bb76614d797dec6df5eb581d88d Mon Sep 17 00:00:00 2001 From: ladvoc <3182119+ladvoc@users.noreply.github.com> Date: Sat, 14 Sep 2024 12:41:46 -0700 Subject: [PATCH] Implement discard conflicting initializer --- .../BijectiveDictionary+Initializers.swift | 15 +++++++++++++++ .../BijectiveDictionaryTests.swift | 7 +++++++ 2 files changed, 22 insertions(+) diff --git a/Sources/BijectiveDictionary/BijectiveDictionary+Initializers.swift b/Sources/BijectiveDictionary/BijectiveDictionary+Initializers.swift index 118e6d6..0d8c0ac 100644 --- a/Sources/BijectiveDictionary/BijectiveDictionary+Initializers.swift +++ b/Sources/BijectiveDictionary/BijectiveDictionary+Initializers.swift @@ -44,6 +44,21 @@ extension BijectiveDictionary { self._rtl = Dictionary(uniqueKeysWithValues: reversePairs) } + /// Creates a new dictionary from the left-right pairs in the given sequence, discarding any conflicting pairs. + /// + /// - Parameter leftRightPairs: A sequence of left-right pairs to use for the new dictionary. + /// - Complexity: O(*n*), where *n* is the number of key-value pairs in the given sequence. + @inlinable public init( + discardConflicting leftRightPairs: S + ) where S: Sequence, S.Element == Element { + self.init() + for pair in leftRightPairs where conflict(with: pair) == nil { + _ltr[pair.left] = pair.right + _rtl[pair.right] = pair.left + } + _invariantCheck() + } + /// Creates a bijective dictionary from a standard dictionary. /// /// Unlike a standard dictionary which only requires its keys be unique, a bijective diff --git a/Tests/BijectiveDictionaryTests/BijectiveDictionaryTests.swift b/Tests/BijectiveDictionaryTests/BijectiveDictionaryTests.swift index f856dbf..2e910f1 100644 --- a/Tests/BijectiveDictionaryTests/BijectiveDictionaryTests.swift +++ b/Tests/BijectiveDictionaryTests/BijectiveDictionaryTests.swift @@ -299,4 +299,11 @@ func conflict() { #expect(dict.conflict(with: ("A", 1)) == .pair) #expect(dict.conflict(with: ("A", 3)) == .both(otherLeft: "C", otherRight: 1)) } + +@Test +func discardConflicting() { + let pairs = [("A", 1), ("B", 1), ("A", 10), ("C", 4), ("C", 4), ("E", 5), ("A", 5)] + let dict = BijectiveDictionary(discardConflicting: pairs) + #expect(dict == ["A": 1, "C": 4, "E": 5]) +} #endif