Skip to content

Instantly share code, notes, and snippets.

@RoshanNindrai
Created March 7, 2018 05:58
Show Gist options
  • Save RoshanNindrai/d076c4a00083dd8e2f34e978eefb94b9 to your computer and use it in GitHub Desktop.
Save RoshanNindrai/d076c4a00083dd8e2f34e978eefb94b9 to your computer and use it in GitHub Desktop.
public protocol ComposableCache {
associatedtype Key
associatedtype Value
var getC: (Key) -> Value? { get set }
var setC: (Key, Value) -> Void { get set }
init(getC: @escaping (Key) -> Value?, setC: @escaping ((Key, Value) -> Void))
func get(_ key: Key) -> Value?
func set(_ key: Key, _ value: Value)
}
precedencegroup ComposePredecesor {
associativity: left
}
infix operator |&: ComposePredecesor
func |&<A: ComposableCache, B: ComposableCache>(_ left: A, _ right: B) -> A where A.Key == B.Key, A.Value == B.Value {
return left.compose(right)
}
extension ComposableCache {
func compose<A: ComposableCache>(_ second: A) -> Self where A.Key == Self.Key, A.Value == Self.Value {
return Self.init(getC: { key in
if let value = self.getC(key) {
return value
} else if let deepValue = second.getC(key) {
self.setC(key, deepValue)
return deepValue
}
return nil
}, setC: { key, value in
self.setC(key, value)
second.setC(key, value)
})
}
func get(_ key: Key) -> Value? {
return getC(key)
}
func set(_ key: Key, _ value: Value) {
setC(key, value)
}
}
struct MemoryComposableCache<K, V>: ComposableCache {
var getC: (K) -> V?
var setC: (K, V) -> Void
typealias Key = K
typealias Value = V
}
struct DiscComposableCache<K, V>: ComposableCache {
var getC: (K) -> V?
var setC: (K, V) -> Void
typealias Key = K
typealias Value = V
}
var memory = MemoryComposableCache<String, String>(getC: { key in print("getting value for \(key) in memory"); return nil}, setC: { key, value in print("setting \(value) for \(key) in memory") })
var disc = MemoryComposableCache<String, String>(getC: { key in print("getting value for \(key) in disc"); return "default"}, setC: { key, value in print("setting \(value) for \(key) in disc") })
let composed = memory |& disc
composed.get("sample key")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment