Create extractLede function on PostListModel

This commit is contained in:
Angelo Stavrow 2020-11-05 16:49:08 -05:00
parent 8f0d21c5e1
commit 3799a0e792
No known key found for this signature in database
GPG Key ID: 1A49C7064E060EEE

View File

@ -18,4 +18,45 @@ class PostListModel: ObservableObject {
print("Error: Failed to purge cached posts.")
}
}
func getBodyPreview(of post: WFAPost) -> String {
var elidedPostBody: String = ""
// Strip any markdown from the post body.
let strippedPostBody = stripMarkdown(from: post.body)
// Get the first 80 characters.
let firstEightyChars = String(strippedPostBody.prefix(80))
// Extract lede from post.
elidedPostBody = extractLede(from: firstEightyChars)
return elidedPostBody
}
}
private extension PostListModel {
func stripMarkdown(from string: String) -> String {
return string
}
func extractLede(from string: String) -> String {
let terminatingCharacters = CharacterSet(charactersIn: ".。?").union(.newlines)
var lede: String
let sentences = string.components(separatedBy: terminatingCharacters)
let firstSentence = sentences.filter { !$0.isEmpty }[0]
if firstSentence == string {
let endOfStringIndex = string.lastIndex(of: " ")
lede = String(string[..<(endOfStringIndex ?? string.index(string.endIndex, offsetBy: -2))]) + ""
} else {
lede = firstSentence
}
return lede
}
}