Skip to content

Commit 487fa73

Browse files
authored
Merge pull request #23 from harlanhaskins/harlan/initial-on-the-dotted-line
Handle title case words after initialisms
2 parents 68b1f1d + 5742196 commit 487fa73

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

Diff for: Sources/Spices/Internal/String+Helpers.swift

+16-5
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,26 @@ extension String {
1313
var pieces = [String]()
1414
var currentPiece = ""
1515

16-
for (idx, character) in enumerated() {
17-
if idx == 0 {
16+
for (idx, character) in zip(indices, self) {
17+
if idx == startIndex {
1818
currentPiece += character.uppercased()
1919
} else if character.isUppercase {
2020
// Small check: recognize runs of multiple uppercase letters and
21-
// consider them part of the same word.
22-
if let previousChar = currentPiece.last, previousChar.isUppercase {
21+
// consider them part of the same word until the start of the next word.
22+
let previousIndex = index(before: idx)
23+
let nextIndex = index(after: idx)
24+
let previous = self[previousIndex]
25+
let next = nextIndex < endIndex ? self[nextIndex] : nil
26+
if previous.isUppercase && next?.isLowercase == true {
27+
// Previous word was an initialism, and this uppercase letter starts a new word
28+
// containing the next character.
29+
pieces.append(currentPiece)
30+
currentPiece = String(character)
31+
} else if previous.isUppercase {
32+
// Continue the initialism.
2333
currentPiece.append(character)
2434
} else {
35+
// Previous word was not an initialism, start a new word.
2536
pieces.append(currentPiece)
2637
currentPiece = character.uppercased()
2738
}
@@ -30,7 +41,7 @@ extension String {
3041
}
3142
}
3243

33-
// Commit the last bit of the phrase
44+
// Commit the last bit of the phrase.
3445
if !currentPiece.isEmpty {
3546
pieces.append(currentPiece)
3647
}

Diff for: Tests/SpicesTests/CamelCaseToNaturalTextTests.swift

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ struct CamelCaseToNaturalTextTests {
1515
#expect("featureFlags".camelCaseToNaturalText() == "Feature Flags")
1616
#expect("notifications".camelCaseToNaturalText() == "Notifications")
1717
#expect("fastRefreshWidgets".camelCaseToNaturalText() == "Fast Refresh Widgets")
18+
#expect("ignoreNextHTTPRequest".camelCaseToNaturalText() == "Ignore Next HTTP Request")
1819

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

0 commit comments

Comments
 (0)