swift-algorithms icon indicating copy to clipboard operation
swift-algorithms copied to clipboard

`uniqued(on:)` is missing a `uniquingWith` overload.

Open JessyCatterwaul opened this issue 3 years ago • 1 comments

With dictionaries, we have a uniquingKeysWith parameter. It would be helpful to have similar for uniqued.

This came up in a Stack Overflow Q/A. The following works but relies on arrays—we should have something better in Algorithms.

import struct OrderedCollections.OrderedDictionary

public extension Sequence {
  @inlinable func uniqued<Subject: Hashable>(
    on projection: (Element) throws -> Subject,
    uniquingWith combine: (Element, Element) throws -> Element
  ) rethrows -> [Element] {
    try OrderedDictionary(keyed(by: projection), uniquingKeysWith: combine)
      .values
      .elements
  }
}
public extension Sequence {
  @inlinable func keyed<Key: Hashable>(
    by key: (Element) throws -> Key
  ) rethrows -> [KeyValuePairs<Key, Element>.Element] {
    try map { (try key($0), $0) }
  }
}

JessyCatterwaul avatar May 22 '22 19:05 JessyCatterwaul

+1, keyed also has a resolvingConflictWith parameter, so not having this on uniqued is quite inconsistent.

Jon889 avatar Dec 09 '24 13:12 Jon889