Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

uniqued(on:) is missing a uniquingWith overload. #188

Open
JessyCatterwaul opened this issue May 22, 2022 · 0 comments
Open

uniqued(on:) is missing a uniquingWith overload. #188

JessyCatterwaul opened this issue May 22, 2022 · 0 comments

Comments

@JessyCatterwaul
Copy link

JessyCatterwaul commented May 22, 2022

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) }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant