Last active
August 19, 2016 02:55
-
-
Save naoty/a3d803f35c687d7c6c2963f24bfe4d62 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
extension String { | |
enum TruncationPosition { | |
case Head | |
case Middle | |
case Tail | |
} | |
func truncated(limit: Int, position: TruncationPosition = .Tail, leader: String = "...") -> String { | |
guard self.characters.count > limit else { | |
return self | |
} | |
switch position { | |
case .Head: | |
let truncated = substringFromIndex(startIndex.advancedBy(limit - leader.characters.count)) | |
return leader + truncated | |
case .Middle: | |
let headCharactersCount = Int(ceil(Float(limit - leader.characters.count) / 2.0)) | |
let head = substringToIndex(startIndex.advancedBy(headCharactersCount)) | |
let tailCharactersCount = Int(floor(Float(limit - leader.characters.count) / 2.0)) | |
let tail = substringFromIndex(endIndex.advancedBy(-tailCharactersCount)) | |
return head + leader + tail | |
case .Tail: | |
let truncated = substringToIndex(startIndex.advancedBy(limit - leader.characters.count)) | |
return truncated + leader | |
} | |
} | |
} |
This file contains hidden or 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
class StringSpec: QuickSpec { | |
override func spec() { | |
describe("-truncated(_:leader:position:)") { | |
let string = "abcdefghij" | |
it("returns a String truncated at head") { | |
let expected = "...fghij" | |
expect(string.truncated(8, position: .Head)).to(equal(expected)) | |
} | |
it("returns a String truncated at middle") { | |
let expected = "abc...ij" | |
expect(string.truncated(8, position: .Middle)).to(equal(expected)) | |
} | |
it("returns a String truncated at tail") { | |
let expected = "abcde..." | |
expect(string.truncated(8, position: .Tail)).to(equal(expected)) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment