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

Handle title case words after initialisms #23

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions Sources/Spices/Internal/String+Helpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,26 @@ extension String {
var pieces = [String]()
var currentPiece = ""

for (idx, character) in enumerated() {
if idx == 0 {
for (idx, character) in zip(indices, self) {
if idx == startIndex {
currentPiece += character.uppercased()
} else if character.isUppercase {
// Small check: recognize runs of multiple uppercase letters and
// consider them part of the same word.
if let previousChar = currentPiece.last, previousChar.isUppercase {
// consider them part of the same word until the start of the next word.
let previousIndex = index(before: idx)
let nextIndex = index(after: idx)
let previous = self[previousIndex]
let next = nextIndex < endIndex ? self[nextIndex] : nil
if previous.isUppercase && next?.isLowercase == true {
// Previous word was an initialism, and this uppercase letter starts a new word
// containing the next character.
pieces.append(currentPiece)
currentPiece = String(character)
} else if previous.isUppercase {
// Continue the initialism.
currentPiece.append(character)
} else {
// Previous word was not an initialism, start a new word.
pieces.append(currentPiece)
currentPiece = character.uppercased()
}
Expand All @@ -30,7 +41,7 @@ extension String {
}
}

// Commit the last bit of the phrase
// Commit the last bit of the phrase.
if !currentPiece.isEmpty {
pieces.append(currentPiece)
}
Expand Down
1 change: 1 addition & 0 deletions Tests/SpicesTests/CamelCaseToNaturalTextTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ struct CamelCaseToNaturalTextTests {
#expect("featureFlags".camelCaseToNaturalText() == "Feature Flags")
#expect("notifications".camelCaseToNaturalText() == "Notifications")
#expect("fastRefreshWidgets".camelCaseToNaturalText() == "Fast Refresh Widgets")
#expect("ignoreNextHTTPRequest".camelCaseToNaturalText() == "Ignore Next HTTP Request")

// Suboptimal, but heuristics for these would be annoying.
#expect("httpVersion".camelCaseToNaturalText() == "Http Version")
Expand Down
Loading