From 6142869b83c412864e4251d67902d3110dff124b Mon Sep 17 00:00:00 2001 From: Konrad `ktoso` Malawski Date: Tue, 16 Aug 2022 20:37:44 +0900 Subject: [PATCH] +OrderedSet add filter #158 --- .../OrderedSet/OrderedSet.swift | 23 +++++++++++++++++++ .../OrderedSet/OrderedSetTests.swift | 18 +++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift index 9e3965bbb..c5f7c6053 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift @@ -494,3 +494,26 @@ extension OrderedSet { return _elements.remove(at: index) } } + +extension OrderedSet { + /// Returns a new ordered set containing the values pairs of the ordered set + /// that satisfy the given predicate. + /// + /// - Parameter isIncluded: A closure that takes a value as its + /// argument and returns a Boolean value indicating whether the value + /// should be included in the returned dictionary. + /// + /// - Returns: An ordered set of the values that `isIncluded` allows. + /// + /// - Complexity: O(`count`) + @inlinable + public func filter( + _ isIncluded: (Element) throws -> Bool + ) rethrows -> Self { + var result: OrderedSet = Self(minimumCapacity: _minimumCapacity) + for element in self where try isIncluded(element) { + result._appendNew(element) + } + return result + } +} diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift index f2161dc3d..2ed48c8c1 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift @@ -1360,4 +1360,22 @@ class OrderedSetTests: CollectionTestCase { } } } + + + func test_filter() { + let items = (0 ..< 100) + let s = OrderedSet(items) + + var c = 0 + let s2 = s.filter { item in + c += 1 + return item.isMultiple(of: 2) + } + expectEqual(c, 100) + expectEqualElements(s, items) + + expectEqualElements(s2, (0 ..< 50).compactMap { key in + return (2 * key) + }) + } }