Skip to content

Instantly share code, notes, and snippets.

@umurgdk
Created December 27, 2023 17:08
Show Gist options
  • Save umurgdk/681f0056ac91ebf6e74d9dc3741ac290 to your computer and use it in GitHub Desktop.
Save umurgdk/681f0056ac91ebf6e74d9dc3741ac290 to your computer and use it in GitHub Desktop.
Compact occurrences of characters to given maximum in Swift
// Created by Umur Gedik on 27.12.2023.
import Foundation
public extension StringProtocol {
func compact(occurencesOf needle: Character, to maxNeedles: Int) -> String {
var parts: [Self.SubSequence] = []
var cursor: String.Index = startIndex
while let needleIndex = self[cursor...].firstIndex(of: needle) {
if needleIndex != cursor {
parts.append(self[cursor..<needleIndex])
}
let nextNonNeedleIndex = self[needleIndex...]
.dropFirst()
.firstIndex(where: { $0 != needle }) ?? endIndex
let numNeedles = distance(from: needleIndex, to: nextNonNeedleIndex)
let inclusiveIndex = index(needleIndex, offsetBy: Swift.min(numNeedles, maxNeedles))
parts.append(self[needleIndex..<inclusiveIndex])
cursor = nextNonNeedleIndex
}
if cursor < endIndex {
parts.append(self[cursor..<endIndex])
}
return parts.joined()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment