The goal is to find the new messages compared to the old ones.
When you try to make an online chat work in your app you need to append the new messages in a tableView, but if you ask the server to send you the latest X messages you don't know which are new and which are old.
Therefore the goal is to return just the new messages in the fastest way possible.
There is one catch though. When all the messages are new you have to assume that there can be more so you return completed false. When in theory you send another request and with the timestamp of the oldest of the messages in the batch.
Also the returned messages should be sorted chronologically by the newest one on 0th spot.
func newMessages(listOf messages: [Message], newestDisplayed message: Message, batchlimit: Int) -> (completed: Bool, newMessages: [Message]) {
let filteredMessages = Set<Message>(messages).subtracting([message]).sorted(by: {$0.timestamp > $1.timestamp})
return (completed: !(filteredMessages.count == batchlimit), newMessages: Array(filteredMessages))
}
struct Message: Hashable {
let id: Int
let timestamp: Int
init(id: Int, timestamp: Int) throws {
self.id = id
self.timestamp = timestamp
}
var hashValue: Int {
return id.hashValue ^ timestamp.hashValue &* 16777619
}
}
extension Message: Equatable {
static func == (lhs: Message, rhs: Message) -> Bool {
return lhs.id == rhs.id
}
}
import XCTest
class SolutionTest: XCTestCase {
static var allTests = [
("Test Example", testExample),
]
func testExample() {
let actual = 1
XCTAssertEqual(actual, 1)
}
}
XCTMain([
testCase(SolutionTest.allTests)
])