Created
February 3, 2016 22:01
-
-
Save marktrobinson/cd23e67804f30ed04217 to your computer and use it in GitHub Desktop.
Optimistic Updating History for Redux SwiftFlow
This file contains 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
import UIKit | |
struct HistoryItem: Equatable { | |
let action: Int | |
let state: String | |
init(action: Int, state: String) { | |
self.action = action | |
self.state = state | |
} | |
} | |
func == (lhs: HistoryItem, rhs: HistoryItem) -> Bool { | |
return lhs.action == rhs.action | |
} | |
struct History { | |
typealias Element = HistoryItem | |
var tail: Int = -1 | |
let maxSize: Int | |
private var buffer: [Element] = [ ] | |
init(withSize size: Int) { | |
self.maxSize = size | |
} | |
var canInsert: Bool { | |
return tail < maxSize - 1 | |
} | |
var isEmpty: Bool { | |
return tail < 0 | |
} | |
mutating func insert(e: Element) { | |
func tailInsert(e: Element) { | |
tail += 1 | |
buffer.append(e) | |
} | |
guard canInsert else { | |
tailInsert(e) | |
resetBuffer() | |
return | |
} | |
tailInsert(e) | |
} | |
mutating func remove(e: Element) { | |
if let index = buffer.indexOf(e) { | |
buffer.removeAtIndex(index) | |
tail -= 1 | |
} | |
} | |
mutating func getReplayBuffer(withoutItem e: HistoryItem) -> [HistoryItem]? { | |
guard !isEmpty, let index = buffer.indexOf(e) else { | |
return nil | |
} | |
guard index != tail else { | |
let newBuffer = Array(arrayLiteral: buffer[tail]) | |
resetBuffer(withNewBuffer: newBuffer) | |
return newBuffer | |
} | |
let newBuffer = Array(buffer[index...tail]) | |
resetBuffer(withNewBuffer: newBuffer) | |
return newBuffer | |
} | |
mutating func resetBuffer(withNewBuffer newBuffer: [HistoryItem]? = nil) { | |
guard let newBuffer = newBuffer else { | |
buffer = Array(buffer[1...tail]) | |
return | |
} | |
buffer = newBuffer | |
tail = newBuffer.count - 1 | |
} | |
func peek() -> Element? { | |
guard !isEmpty else { | |
return nil | |
} | |
return buffer.first | |
} | |
} | |
var h = History(withSize: 5) | |
var item1 = HistoryItem(action: 1, state: "first") | |
var item2 = HistoryItem(action: 2, state: "second") | |
var item3 = HistoryItem(action: 3, state: "third") | |
h.insert(item1) | |
h.insert(item2) | |
h.insert(item3) | |
let replay = h.getReplayBuffer(withoutItem: item2) | |
let x = replay?.map({ $0.state }) | |
print(x!) | |
print(h.tail) | |
let r2 = h.getReplayBuffer(withoutItem: item3) | |
let y = r2?.map({ $0.state }) | |
print(y!) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Still a work in progress, this is how far I got though