Skip to content

Commit

Permalink
Fixing underscore prefixes in names of fields
Browse files Browse the repository at this point in the history
  • Loading branch information
nerdsupremacist committed Jan 20, 2021
1 parent aa7bd9d commit b57a1cb
Showing 1 changed file with 34 additions and 8 deletions.
42 changes: 34 additions & 8 deletions Sources/Graphaello/Extensions/String+camelized.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import Foundation

// Copied and adapted from https://gist.github.com/reitzig/67b41e75176ddfd432cb09392a270218
// Modifications made public at: https://gist.github.com/nerdsupremacist/8e620beb2dcf6404f9edcac756ed28dc
fileprivate let badChars = CharacterSet.alphanumerics.inverted
private let badChars = CharacterSet.alphanumerics.inverted
private let allowedPrefixBadChars: CharacterSet = ["_"]

extension String {
var uppercasingFirst: String {
Expand All @@ -20,43 +21,68 @@ extension String {

guard uppercased() != self else { return lowercased() }

let parts = self.parts
let (prefix, parts) = nameParts()
let first = String(describing: parts.first!).lowercasingFirst
let rest = parts.dropFirst().map({String($0).uppercasingFirst})

return ([first] + rest).joined(separator: "")
return ([prefix, first] + rest).joined(separator: "")
}

var upperCamelized: String {
guard !isEmpty else {
return ""
}

return parts.map { String($0).uppercasingFirst }.joined(separator: "")
let (prefix, parts) = nameParts()
return prefix + parts.map { String($0).uppercasingFirst }.joined(separator: "")
}

var snakeCased: String {
guard !isEmpty else {
return ""
}

return parts.map { String($0).lowercased() }.joined(separator: "_")
let (prefix, parts) = nameParts()
return prefix + parts.map { String($0).lowercased() }.joined(separator: "_")
}


var snakeUpperCased: String {
return snakeCased.uppercased()
}

private var parts: [String] {
let basics = replacingOccurrences(of: "([a-z])([A-Z])",
private func nameParts() -> (prefix: String, parts: [String]) {
let (prefix, rest) = splitPrefix(of: allowedPrefixBadChars)

let basics = rest.replacingOccurrences(of: "([a-z])([A-Z])",
with: "$1 $2",
options: .regularExpression)

let complete = basics.replacingOccurrences(of: "([A-Z]+)([A-Z][a-z]|$)",
with: "$1 $2",
options: .regularExpression)

return complete.components(separatedBy: badChars).filter { !$0.isEmpty }
return (
prefix,
complete.components(separatedBy: badChars).filter { !$0.isEmpty }
)
}

private func splitPrefix(of characterSet: CharacterSet) -> (prefix: String, new: String) {
guard !isEmpty else { return (self, self) }
let splitIndex = firstIndex { !characterSet.contains($0) } ?? endIndex

return (
String(self[startIndex..<splitIndex]),
String(self[splitIndex...])
)
}
}

extension CharacterSet {

fileprivate func contains(_ character: Character) -> Bool {
return character.unicodeScalars.allSatisfy { contains($0) }
}

}

0 comments on commit b57a1cb

Please sign in to comment.