Skip to content

Instantly share code, notes, and snippets.

@chug2k
Created October 11, 2017 08:47
Show Gist options
  • Save chug2k/4c71e2811e6fc31b1b0b409de3bfca2a to your computer and use it in GitHub Desktop.
Save chug2k/4c71e2811e6fc31b1b0b409de3bfca2a to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
let CHARACTER_LIMIT = 7
let text = "a b c d e f g h i j k"
class TweetComponent: CustomStringConvertible {
var content: String
let index: Int
let maxPages: Int
var prefix: String {
return "\(index)/\(maxPages) "
}
var characterLimit: Int {
return CHARACTER_LIMIT - prefix.characters.count
}
init(content: String, index: Int, maxPages: Int) {
self.content = content
self.index = index
self.maxPages = maxPages
if content.characters.count > characterLimit {
print("ERROR \(content) too long, it needs to be \(characterLimit)")
}
}
func append(str: String) -> Bool {
let proposedSentence = "\(content) \(str)"
if proposedSentence.characters.count <= characterLimit {
content = proposedSentence
return true
}
return false
}
public var description: String {
return "\(prefix)\(content)"
}
}
func split(inputStr: String, maxPages: Int=1) -> [TweetComponent] {
var words = inputStr.components(separatedBy: .whitespacesAndNewlines)
// Initialize the first component manually. We'll fix up maxPages later.
var ret: [TweetComponent] = [TweetComponent.init(content: words.remove(at: 0), index: 1, maxPages: maxPages)]
for word in words {
let last = ret.last!
// A try catch here would be nicer, perhaps.
let success = last.append(str: word)
if !success {
ret.append(TweetComponent.init(content: word, index: ret.count + 1, maxPages: maxPages))
}
}
if ret.count > maxPages {
return split(inputStr: inputStr, maxPages: ret.count)
}
return ret
}
func prettyPrint(strArr: [TweetComponent]) {
for tweet in strArr {
print("\(tweet) (length: \(tweet.description.characters.count))")
}
print("total is \(strArr.count)")
}
prettyPrint(strArr: split(inputStr: text))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment