apple / swift-algorithms

Commonly used sequence and collection algorithms for Swift
Apache License 2.0
5.97k stars 443 forks source link

Split a collection using a collection separator #155

Closed timvermeulen closed 1 year ago

timvermeulen commented 3 years ago

Depends on #154.

Note that the overload on LazyCollectionProtocol returns a LazyCollection<SplitCollection<Elements, Separator>> rather than a SplitCollection<Self, Separator>. The purpose of this is to have it return slices of the underlying collection, rather than slices of the lazy wrapper.

We'll also need to unify the name of the type added here (currently SplitCollection) with the type returned by the lazy split operation that takes a single element separator (currently LazySplitCollection).

extension Collection {
  public func split<Separator: Collection>(
    separator: Separator,
    maxSplits: Int = Int.max,
    omittingEmptySubsequences: Bool = true,
    by areEquivalent: (Element, Separator.Element) throws -> Bool
  ) rethrows -> [SubSequence]
}

extension Collection where Element: Equatable {
  public func split<Separator: Collection>(
    separator: Separator,
    maxSplits: Int = Int.max,
    omittingEmptySubsequences: Bool = true
  ) -> SplitCollection<Self, Separator>
    where Separator.Element == Element
}

extension LazyCollectionProtocol {
  public func split<Separator: Collection>(
    separator: Separator,
    maxSplits: Int = Int.max,
    omittingEmptySubsequences: Bool = true,
    by areEquivalent: @escaping (Element, Separator.Element) -> Bool
  ) -> LazyCollection<SplitCollection<Elements, Separator>>
}

extension LazyCollectionProtocol where Element: Equatable {
  public func split<Separator: Collection>(
    separator: Separator,
    maxSplits: Int = Int.max,
    omittingEmptySubsequences: Bool = true
  ) -> LazyCollection<SplitCollection<Elements, Separator>>
    where Separator.Element == Element
}

Checklist

natecook1000 commented 1 year ago

This functionality is now covered by the string-processing package.