Skip to content

Commit

Permalink
+OrderedSet add filter apple#158
Browse files Browse the repository at this point in the history
  • Loading branch information
ktoso committed Aug 16, 2022
1 parent f8ac3af commit 6142869
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
23 changes: 23 additions & 0 deletions Sources/OrderedCollections/OrderedSet/OrderedSet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
18 changes: 18 additions & 0 deletions Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
}
}

0 comments on commit 6142869

Please sign in to comment.