Created
December 27, 2023 17:08
-
-
Save umurgdk/681f0056ac91ebf6e74d9dc3741ac290 to your computer and use it in GitHub Desktop.
Compact occurrences of characters to given maximum in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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